R - How do I pass a function as an argument to another function?How do JavaScript closures work?What's the difference between a method and a function?var functionName = function() vs function functionName() Set a default parameter value for a JavaScript functionWhat does the exclamation mark do before the function?How to pass all arguments passed to my bash script to a function of mine?How to make a great R reproducible exampleHow can we make xkcd style graphs?Pass a JavaScript function as parametergeom_histogram: wrong bins?

If someone asks a question using “quién”, how can one shortly respond?

Can you cure a Gorgon's Petrifying Breath before it finishes turning a target to stone?

French license plates

Diminished data rate with logic output optoisolator

What does it mean by "my days-of-the-week underwear only go to Thursday" in this context?

Verb ending in -ん with positive meaning?

How to compare integers in TeX?

How to level a picture frame hung on a single nail?

Garage door sticks on a bolt

Can the President of the US limit First Amendment rights?

Is it good to engage in exceptional cases where it is permissible to do a typically forbidden action to which one has a taivah for

Why does `FindFit` fail so badly in this simple case?

Implementation of a Thread Pool in C++

does 'java' command compile the java program?

Was the ruling that prorogation was unlawful only possible because of the creation of a separate supreme court?

Do my potential customers need to understand the "meaning" of a logo, or just recognize it?

Replacing cord for IBM model M keyboard

Impossible violin chord, how to fix this?

IEEE 754 square root with Newton-Raphson

As a team leader is it appropriate to bring in fundraiser candy?

Smallest PRIME containing the first 11 primes as sub-strings

How big would the ice ball have to be to deliver all the water at once?

Convert a string of digits from words to an integer

Phonetic distortion when words are borrowed among languages



R - How do I pass a function as an argument to another function?


How do JavaScript closures work?What's the difference between a method and a function?var functionName = function() vs function functionName() Set a default parameter value for a JavaScript functionWhat does the exclamation mark do before the function?How to pass all arguments passed to my bash script to a function of mine?How to make a great R reproducible exampleHow can we make xkcd style graphs?Pass a JavaScript function as parametergeom_histogram: wrong bins?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have a function I'm creating like this:



library(ggplot2)
plot_function <- function(data, x, y)
ggplot(data, aes_string(x=x, y=y)) +
geom_line() +
scale_y_continuous(labels = scales::comma_format())



I can call it like this:



df <- data.frame(date = seq(as.Date("2019/01/01"), as.Date("2019/01/05"),"1 day"), 
value = seq(.1,.5, .1))

df

date value
2019-01-01 0.1
2019-01-02 0.2
2019-01-03 0.3
2019-01-04 0.4
2019-01-05 0.5

plot_function(df, x = "date", "value")


enter image description here



But what if I wanted to allow the user to be able to change the y axis to a percentage. How can I let them replace scales::comma_format()? This doesn't work:



plot_function <- function(data, x, y, y_format)

ggplot(data, aes_string(x=x, y=y)) +
geom_line() +
scale_y_continuous(labels = y_format)


plot_function(df, x = "date", "value", y_format = "scales::percent_format()")


I get this error:



"Error in f(..., self = self) : Breaks and labels are different lengths"









share|improve this question


























  • What happens when you pass the function itself by removing the quotes?

    – joran
    Mar 28 at 20:08











  • Your solution would have worked if you just left the quotes off. plot_function(df, x = "date", "value", y_format = scales::percent_format()). It's important to note that scales::percent_format() itself is calling a function that returns a function.

    – MrFlick
    Mar 29 at 2:19

















2















I have a function I'm creating like this:



library(ggplot2)
plot_function <- function(data, x, y)
ggplot(data, aes_string(x=x, y=y)) +
geom_line() +
scale_y_continuous(labels = scales::comma_format())



I can call it like this:



df <- data.frame(date = seq(as.Date("2019/01/01"), as.Date("2019/01/05"),"1 day"), 
value = seq(.1,.5, .1))

df

date value
2019-01-01 0.1
2019-01-02 0.2
2019-01-03 0.3
2019-01-04 0.4
2019-01-05 0.5

plot_function(df, x = "date", "value")


enter image description here



But what if I wanted to allow the user to be able to change the y axis to a percentage. How can I let them replace scales::comma_format()? This doesn't work:



plot_function <- function(data, x, y, y_format)

ggplot(data, aes_string(x=x, y=y)) +
geom_line() +
scale_y_continuous(labels = y_format)


plot_function(df, x = "date", "value", y_format = "scales::percent_format()")


I get this error:



"Error in f(..., self = self) : Breaks and labels are different lengths"









share|improve this question


























  • What happens when you pass the function itself by removing the quotes?

    – joran
    Mar 28 at 20:08











  • Your solution would have worked if you just left the quotes off. plot_function(df, x = "date", "value", y_format = scales::percent_format()). It's important to note that scales::percent_format() itself is calling a function that returns a function.

    – MrFlick
    Mar 29 at 2:19













2












2








2








I have a function I'm creating like this:



library(ggplot2)
plot_function <- function(data, x, y)
ggplot(data, aes_string(x=x, y=y)) +
geom_line() +
scale_y_continuous(labels = scales::comma_format())



I can call it like this:



df <- data.frame(date = seq(as.Date("2019/01/01"), as.Date("2019/01/05"),"1 day"), 
value = seq(.1,.5, .1))

df

date value
2019-01-01 0.1
2019-01-02 0.2
2019-01-03 0.3
2019-01-04 0.4
2019-01-05 0.5

plot_function(df, x = "date", "value")


enter image description here



But what if I wanted to allow the user to be able to change the y axis to a percentage. How can I let them replace scales::comma_format()? This doesn't work:



plot_function <- function(data, x, y, y_format)

ggplot(data, aes_string(x=x, y=y)) +
geom_line() +
scale_y_continuous(labels = y_format)


plot_function(df, x = "date", "value", y_format = "scales::percent_format()")


I get this error:



"Error in f(..., self = self) : Breaks and labels are different lengths"









share|improve this question
















I have a function I'm creating like this:



library(ggplot2)
plot_function <- function(data, x, y)
ggplot(data, aes_string(x=x, y=y)) +
geom_line() +
scale_y_continuous(labels = scales::comma_format())



I can call it like this:



df <- data.frame(date = seq(as.Date("2019/01/01"), as.Date("2019/01/05"),"1 day"), 
value = seq(.1,.5, .1))

df

date value
2019-01-01 0.1
2019-01-02 0.2
2019-01-03 0.3
2019-01-04 0.4
2019-01-05 0.5

plot_function(df, x = "date", "value")


enter image description here



But what if I wanted to allow the user to be able to change the y axis to a percentage. How can I let them replace scales::comma_format()? This doesn't work:



plot_function <- function(data, x, y, y_format)

ggplot(data, aes_string(x=x, y=y)) +
geom_line() +
scale_y_continuous(labels = y_format)


plot_function(df, x = "date", "value", y_format = "scales::percent_format()")


I get this error:



"Error in f(..., self = self) : Breaks and labels are different lengths"






r function ggplot2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 21:34









camille

10.1k7 gold badges21 silver badges38 bronze badges




10.1k7 gold badges21 silver badges38 bronze badges










asked Mar 28 at 20:07









Jacob CurtisJacob Curtis

3701 gold badge2 silver badges13 bronze badges




3701 gold badge2 silver badges13 bronze badges















  • What happens when you pass the function itself by removing the quotes?

    – joran
    Mar 28 at 20:08











  • Your solution would have worked if you just left the quotes off. plot_function(df, x = "date", "value", y_format = scales::percent_format()). It's important to note that scales::percent_format() itself is calling a function that returns a function.

    – MrFlick
    Mar 29 at 2:19

















  • What happens when you pass the function itself by removing the quotes?

    – joran
    Mar 28 at 20:08











  • Your solution would have worked if you just left the quotes off. plot_function(df, x = "date", "value", y_format = scales::percent_format()). It's important to note that scales::percent_format() itself is calling a function that returns a function.

    – MrFlick
    Mar 29 at 2:19
















What happens when you pass the function itself by removing the quotes?

– joran
Mar 28 at 20:08





What happens when you pass the function itself by removing the quotes?

– joran
Mar 28 at 20:08













Your solution would have worked if you just left the quotes off. plot_function(df, x = "date", "value", y_format = scales::percent_format()). It's important to note that scales::percent_format() itself is calling a function that returns a function.

– MrFlick
Mar 29 at 2:19





Your solution would have worked if you just left the quotes off. plot_function(df, x = "date", "value", y_format = scales::percent_format()). It's important to note that scales::percent_format() itself is calling a function that returns a function.

– MrFlick
Mar 29 at 2:19












2 Answers
2






active

oldest

votes


















2
















try this:



plot_function <- function(data, x, y, y_format)

ggplot(data, aes_string(x=x, y=y)) +
geom_line() +
scale_y_continuous(labels = y_format())



plot_function(df, x = "date", "value", y_format = scales::percent_format)





share|improve this answer
































    3
















    Another option is to set up the function using the ... argument, so that passing a labels argument to scale_y_continuous is optional:



    plot_function <- function(data, x, y, ...) 

    ggplot(data, aes_string(x=x, y=y)) +
    geom_line() +
    scale_y_continuous(...)


    # Pass nothing to scale_y_continuous
    plot_function(mtcars, x = "cyl", y="hp")

    # Add some big numbers to mtcars
    mtcars$hp = 1e5 * mtcars$hp

    # Pass a labels argument to scale_y_continuous to get comma formatted values
    plot_function(mtcars, x = "cyl", y="hp", labels=scales::comma)





    share|improve this answer



























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );














      draft saved

      draft discarded
















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406039%2fr-how-do-i-pass-a-function-as-an-argument-to-another-function%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2
















      try this:



      plot_function <- function(data, x, y, y_format)

      ggplot(data, aes_string(x=x, y=y)) +
      geom_line() +
      scale_y_continuous(labels = y_format())



      plot_function(df, x = "date", "value", y_format = scales::percent_format)





      share|improve this answer





























        2
















        try this:



        plot_function <- function(data, x, y, y_format)

        ggplot(data, aes_string(x=x, y=y)) +
        geom_line() +
        scale_y_continuous(labels = y_format())



        plot_function(df, x = "date", "value", y_format = scales::percent_format)





        share|improve this answer



























          2














          2










          2









          try this:



          plot_function <- function(data, x, y, y_format)

          ggplot(data, aes_string(x=x, y=y)) +
          geom_line() +
          scale_y_continuous(labels = y_format())



          plot_function(df, x = "date", "value", y_format = scales::percent_format)





          share|improve this answer













          try this:



          plot_function <- function(data, x, y, y_format)

          ggplot(data, aes_string(x=x, y=y)) +
          geom_line() +
          scale_y_continuous(labels = y_format())



          plot_function(df, x = "date", "value", y_format = scales::percent_format)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 28 at 20:10









          CetttCettt

          5,0175 gold badges18 silver badges41 bronze badges




          5,0175 gold badges18 silver badges41 bronze badges


























              3
















              Another option is to set up the function using the ... argument, so that passing a labels argument to scale_y_continuous is optional:



              plot_function <- function(data, x, y, ...) 

              ggplot(data, aes_string(x=x, y=y)) +
              geom_line() +
              scale_y_continuous(...)


              # Pass nothing to scale_y_continuous
              plot_function(mtcars, x = "cyl", y="hp")

              # Add some big numbers to mtcars
              mtcars$hp = 1e5 * mtcars$hp

              # Pass a labels argument to scale_y_continuous to get comma formatted values
              plot_function(mtcars, x = "cyl", y="hp", labels=scales::comma)





              share|improve this answer





























                3
















                Another option is to set up the function using the ... argument, so that passing a labels argument to scale_y_continuous is optional:



                plot_function <- function(data, x, y, ...) 

                ggplot(data, aes_string(x=x, y=y)) +
                geom_line() +
                scale_y_continuous(...)


                # Pass nothing to scale_y_continuous
                plot_function(mtcars, x = "cyl", y="hp")

                # Add some big numbers to mtcars
                mtcars$hp = 1e5 * mtcars$hp

                # Pass a labels argument to scale_y_continuous to get comma formatted values
                plot_function(mtcars, x = "cyl", y="hp", labels=scales::comma)





                share|improve this answer



























                  3














                  3










                  3









                  Another option is to set up the function using the ... argument, so that passing a labels argument to scale_y_continuous is optional:



                  plot_function <- function(data, x, y, ...) 

                  ggplot(data, aes_string(x=x, y=y)) +
                  geom_line() +
                  scale_y_continuous(...)


                  # Pass nothing to scale_y_continuous
                  plot_function(mtcars, x = "cyl", y="hp")

                  # Add some big numbers to mtcars
                  mtcars$hp = 1e5 * mtcars$hp

                  # Pass a labels argument to scale_y_continuous to get comma formatted values
                  plot_function(mtcars, x = "cyl", y="hp", labels=scales::comma)





                  share|improve this answer













                  Another option is to set up the function using the ... argument, so that passing a labels argument to scale_y_continuous is optional:



                  plot_function <- function(data, x, y, ...) 

                  ggplot(data, aes_string(x=x, y=y)) +
                  geom_line() +
                  scale_y_continuous(...)


                  # Pass nothing to scale_y_continuous
                  plot_function(mtcars, x = "cyl", y="hp")

                  # Add some big numbers to mtcars
                  mtcars$hp = 1e5 * mtcars$hp

                  # Pass a labels argument to scale_y_continuous to get comma formatted values
                  plot_function(mtcars, x = "cyl", y="hp", labels=scales::comma)






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 28 at 20:32









                  eipi10eipi10

                  64.4k17 gold badges122 silver badges187 bronze badges




                  64.4k17 gold badges122 silver badges187 bronze badges































                      draft saved

                      draft discarded















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55406039%2fr-how-do-i-pass-a-function-as-an-argument-to-another-function%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현