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

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript