Pass variables by name into a function that calls dplyr?Is Java “pass-by-reference” or “pass-by-value”?What's the difference between a method and a function?What is the naming convention in Python for variable and function names?var functionName = function() vs function functionName() What is the scope of variables in JavaScript?Set a default parameter value for a JavaScript functionHow do I pass a variable by reference?What is the difference between call and apply?How to pass all arguments passed to my bash script to a function of mine?R dplyr: summarise_each from an external lookup table?

What does the Rambam mean when he says that the planets have souls?

What is the gram­mat­i­cal term for “‑ed” words like these?

Why does Async/Await work properly when the loop is inside the async function and not the other way around?

Does having a TSA Pre-Check member in your flight reservation increase the chances that everyone gets Pre-Check?

How to align and center standalone amsmath equations?

On a tidally locked planet, would time be quantized?

Proving a function is onto where f(x)=|x|.

Journal losing indexing services

Can the Supreme Court overturn an impeachment?

Translation of Scottish 16th century church stained glass

Should I install hardwood flooring or cabinets first?

Why did the EU agree to delay the Brexit deadline?

How can "mimic phobia" be cured or prevented?

Do Legal Documents Require Signing In Standard Pen Colors?

MAXDOP Settings for SQL Server 2014

Is there a word to describe the feeling of being transfixed out of horror?

Varistor? Purpose and principle

Find last 3 digits of this monster number

Why has "pence" been used in this sentence, not "pences"?

Did arcade monitors have same pixel aspect ratio as TV sets?

Could solar power be utilized and substitute coal in the 19th Century

What's the difference between 違法 and 不法?

Aligning individual characters/glyphs like a monospace font

A Permanent Norse Presence in America



Pass variables by name into a function that calls dplyr?


Is Java “pass-by-reference” or “pass-by-value”?What's the difference between a method and a function?What is the naming convention in Python for variable and function names?var functionName = function() vs function functionName() What is the scope of variables in JavaScript?Set a default parameter value for a JavaScript functionHow do I pass a variable by reference?What is the difference between call and apply?How to pass all arguments passed to my bash script to a function of mine?R dplyr: summarise_each from an external lookup table?













1















I'm trying to create a function that will take 2 variables from a dataset, and map their distinct values side by side, after which it will write the out to a csv file. I'll be using dplyr's distinct function for getting the unique values.



map_table <- function(df, var1, var2)
df_distinct <- df %>% distinct(var1, var2)
write.csv(df_distinct, 'var1.csv')


map_table(iris, Species, Petal.Width)


1) map_table(iris, Species, Petal.Width) doesn't produce what I want. It should produce 27 rows of data, instead I'm getting 150 rows of data.



2) How can I name the csv file after the input of var1?
So if var1 = 'Sepal.Length', the name of the file should be 'Sepal.Length.csv'










share|improve this question
























  • non-standard evaluation (NSE) is one well-known hiccup when using dplyr. Here's [one related question from back in 2014](how can i tell select() in dplyr that the string it is seeing is a column name in a data frame); but the solution here is cleaner, so this should probably not be closed-as-duplicate.

    – smci
    Mar 9 at 2:24















1















I'm trying to create a function that will take 2 variables from a dataset, and map their distinct values side by side, after which it will write the out to a csv file. I'll be using dplyr's distinct function for getting the unique values.



map_table <- function(df, var1, var2)
df_distinct <- df %>% distinct(var1, var2)
write.csv(df_distinct, 'var1.csv')


map_table(iris, Species, Petal.Width)


1) map_table(iris, Species, Petal.Width) doesn't produce what I want. It should produce 27 rows of data, instead I'm getting 150 rows of data.



2) How can I name the csv file after the input of var1?
So if var1 = 'Sepal.Length', the name of the file should be 'Sepal.Length.csv'










share|improve this question
























  • non-standard evaluation (NSE) is one well-known hiccup when using dplyr. Here's [one related question from back in 2014](how can i tell select() in dplyr that the string it is seeing is a column name in a data frame); but the solution here is cleaner, so this should probably not be closed-as-duplicate.

    – smci
    Mar 9 at 2:24













1












1








1








I'm trying to create a function that will take 2 variables from a dataset, and map their distinct values side by side, after which it will write the out to a csv file. I'll be using dplyr's distinct function for getting the unique values.



map_table <- function(df, var1, var2)
df_distinct <- df %>% distinct(var1, var2)
write.csv(df_distinct, 'var1.csv')


map_table(iris, Species, Petal.Width)


1) map_table(iris, Species, Petal.Width) doesn't produce what I want. It should produce 27 rows of data, instead I'm getting 150 rows of data.



2) How can I name the csv file after the input of var1?
So if var1 = 'Sepal.Length', the name of the file should be 'Sepal.Length.csv'










share|improve this question
















I'm trying to create a function that will take 2 variables from a dataset, and map their distinct values side by side, after which it will write the out to a csv file. I'll be using dplyr's distinct function for getting the unique values.



map_table <- function(df, var1, var2)
df_distinct <- df %>% distinct(var1, var2)
write.csv(df_distinct, 'var1.csv')


map_table(iris, Species, Petal.Width)


1) map_table(iris, Species, Petal.Width) doesn't produce what I want. It should produce 27 rows of data, instead I'm getting 150 rows of data.



2) How can I name the csv file after the input of var1?
So if var1 = 'Sepal.Length', the name of the file should be 'Sepal.Length.csv'







r function dplyr parameter-passing non-standard-evaluation






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 2:08









smci

15.4k678109




15.4k678109










asked Mar 8 at 6:48









spidermarnspidermarn

664




664












  • non-standard evaluation (NSE) is one well-known hiccup when using dplyr. Here's [one related question from back in 2014](how can i tell select() in dplyr that the string it is seeing is a column name in a data frame); but the solution here is cleaner, so this should probably not be closed-as-duplicate.

    – smci
    Mar 9 at 2:24

















  • non-standard evaluation (NSE) is one well-known hiccup when using dplyr. Here's [one related question from back in 2014](how can i tell select() in dplyr that the string it is seeing is a column name in a data frame); but the solution here is cleaner, so this should probably not be closed-as-duplicate.

    – smci
    Mar 9 at 2:24
















non-standard evaluation (NSE) is one well-known hiccup when using dplyr. Here's [one related question from back in 2014](how can i tell select() in dplyr that the string it is seeing is a column name in a data frame); but the solution here is cleaner, so this should probably not be closed-as-duplicate.

– smci
Mar 9 at 2:24





non-standard evaluation (NSE) is one well-known hiccup when using dplyr. Here's [one related question from back in 2014](how can i tell select() in dplyr that the string it is seeing is a column name in a data frame); but the solution here is cleaner, so this should probably not be closed-as-duplicate.

– smci
Mar 9 at 2:24












3 Answers
3






active

oldest

votes


















2














If you want to pass the col names without quotes, you need to use non-standard evaluation. (More here)



deparse(substitute()) will get you the name for the file output.



library(dplyr)

map_table <- function(df, var1, var2)

file_name <- paste0(deparse(substitute(var1)), ".csv") # file name

var1 <- enquo(var1) # non-standard eval
var2 <- enquo(var2) # equo() caputures the expression passed, ie: Species

df_distinct <- df %>%
distinct(!!var1, !!var2) # non-standard eval, !! tells dplyr to use Species

write.csv(df_distinct, file = file_name)



map_table(iris, Species, Petal.Width)





share|improve this answer






























    0














    You're trying to pass the columns as objects. Try passing their names instead and then use a select helper:



    map_table <- function(df, var1, var2)
    df_distinct <- df %>% select(one_of(c(var1, var2)))%>%
    distinct()
    write.csv(df_distinct, 'var1.csv')


    map_table(iris, 'Species', 'Petal.Width')





    share|improve this answer






























      0














      1) Ok the answer is to use distinct_ instead of distinct. And the variables being called need to be apostrophized.
      2) use apply function to concatenate values/string formatting, and file =



      map_table <- function(df, var1, var2)
      df_distinct <- df %>% distinct_(var1, var2)
      write.csv(df_distinct, file = paste(var1,'.csv'))


      map_table(iris, 'Species', 'Petal.Width')





      share|improve this answer

























      • There's also a solution without the quotes in the function call.

        – RLave
        Mar 8 at 9:09











      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/3.0/"u003ecc by-sa 3.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%2f55058084%2fpass-variables-by-name-into-a-function-that-calls-dplyr%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      If you want to pass the col names without quotes, you need to use non-standard evaluation. (More here)



      deparse(substitute()) will get you the name for the file output.



      library(dplyr)

      map_table <- function(df, var1, var2)

      file_name <- paste0(deparse(substitute(var1)), ".csv") # file name

      var1 <- enquo(var1) # non-standard eval
      var2 <- enquo(var2) # equo() caputures the expression passed, ie: Species

      df_distinct <- df %>%
      distinct(!!var1, !!var2) # non-standard eval, !! tells dplyr to use Species

      write.csv(df_distinct, file = file_name)



      map_table(iris, Species, Petal.Width)





      share|improve this answer



























        2














        If you want to pass the col names without quotes, you need to use non-standard evaluation. (More here)



        deparse(substitute()) will get you the name for the file output.



        library(dplyr)

        map_table <- function(df, var1, var2)

        file_name <- paste0(deparse(substitute(var1)), ".csv") # file name

        var1 <- enquo(var1) # non-standard eval
        var2 <- enquo(var2) # equo() caputures the expression passed, ie: Species

        df_distinct <- df %>%
        distinct(!!var1, !!var2) # non-standard eval, !! tells dplyr to use Species

        write.csv(df_distinct, file = file_name)



        map_table(iris, Species, Petal.Width)





        share|improve this answer

























          2












          2








          2







          If you want to pass the col names without quotes, you need to use non-standard evaluation. (More here)



          deparse(substitute()) will get you the name for the file output.



          library(dplyr)

          map_table <- function(df, var1, var2)

          file_name <- paste0(deparse(substitute(var1)), ".csv") # file name

          var1 <- enquo(var1) # non-standard eval
          var2 <- enquo(var2) # equo() caputures the expression passed, ie: Species

          df_distinct <- df %>%
          distinct(!!var1, !!var2) # non-standard eval, !! tells dplyr to use Species

          write.csv(df_distinct, file = file_name)



          map_table(iris, Species, Petal.Width)





          share|improve this answer













          If you want to pass the col names without quotes, you need to use non-standard evaluation. (More here)



          deparse(substitute()) will get you the name for the file output.



          library(dplyr)

          map_table <- function(df, var1, var2)

          file_name <- paste0(deparse(substitute(var1)), ".csv") # file name

          var1 <- enquo(var1) # non-standard eval
          var2 <- enquo(var2) # equo() caputures the expression passed, ie: Species

          df_distinct <- df %>%
          distinct(!!var1, !!var2) # non-standard eval, !! tells dplyr to use Species

          write.csv(df_distinct, file = file_name)



          map_table(iris, Species, Petal.Width)






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 8 at 9:05









          RLaveRLave

          5,21911226




          5,21911226























              0














              You're trying to pass the columns as objects. Try passing their names instead and then use a select helper:



              map_table <- function(df, var1, var2)
              df_distinct <- df %>% select(one_of(c(var1, var2)))%>%
              distinct()
              write.csv(df_distinct, 'var1.csv')


              map_table(iris, 'Species', 'Petal.Width')





              share|improve this answer



























                0














                You're trying to pass the columns as objects. Try passing their names instead and then use a select helper:



                map_table <- function(df, var1, var2)
                df_distinct <- df %>% select(one_of(c(var1, var2)))%>%
                distinct()
                write.csv(df_distinct, 'var1.csv')


                map_table(iris, 'Species', 'Petal.Width')





                share|improve this answer

























                  0












                  0








                  0







                  You're trying to pass the columns as objects. Try passing their names instead and then use a select helper:



                  map_table <- function(df, var1, var2)
                  df_distinct <- df %>% select(one_of(c(var1, var2)))%>%
                  distinct()
                  write.csv(df_distinct, 'var1.csv')


                  map_table(iris, 'Species', 'Petal.Width')





                  share|improve this answer













                  You're trying to pass the columns as objects. Try passing their names instead and then use a select helper:



                  map_table <- function(df, var1, var2)
                  df_distinct <- df %>% select(one_of(c(var1, var2)))%>%
                  distinct()
                  write.csv(df_distinct, 'var1.csv')


                  map_table(iris, 'Species', 'Petal.Width')






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 8 at 7:04









                  RohitRohit

                  902412




                  902412





















                      0














                      1) Ok the answer is to use distinct_ instead of distinct. And the variables being called need to be apostrophized.
                      2) use apply function to concatenate values/string formatting, and file =



                      map_table <- function(df, var1, var2)
                      df_distinct <- df %>% distinct_(var1, var2)
                      write.csv(df_distinct, file = paste(var1,'.csv'))


                      map_table(iris, 'Species', 'Petal.Width')





                      share|improve this answer

























                      • There's also a solution without the quotes in the function call.

                        – RLave
                        Mar 8 at 9:09
















                      0














                      1) Ok the answer is to use distinct_ instead of distinct. And the variables being called need to be apostrophized.
                      2) use apply function to concatenate values/string formatting, and file =



                      map_table <- function(df, var1, var2)
                      df_distinct <- df %>% distinct_(var1, var2)
                      write.csv(df_distinct, file = paste(var1,'.csv'))


                      map_table(iris, 'Species', 'Petal.Width')





                      share|improve this answer

























                      • There's also a solution without the quotes in the function call.

                        – RLave
                        Mar 8 at 9:09














                      0












                      0








                      0







                      1) Ok the answer is to use distinct_ instead of distinct. And the variables being called need to be apostrophized.
                      2) use apply function to concatenate values/string formatting, and file =



                      map_table <- function(df, var1, var2)
                      df_distinct <- df %>% distinct_(var1, var2)
                      write.csv(df_distinct, file = paste(var1,'.csv'))


                      map_table(iris, 'Species', 'Petal.Width')





                      share|improve this answer















                      1) Ok the answer is to use distinct_ instead of distinct. And the variables being called need to be apostrophized.
                      2) use apply function to concatenate values/string formatting, and file =



                      map_table <- function(df, var1, var2)
                      df_distinct <- df %>% distinct_(var1, var2)
                      write.csv(df_distinct, file = paste(var1,'.csv'))


                      map_table(iris, 'Species', 'Petal.Width')






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Mar 8 at 7:40

























                      answered Mar 8 at 7:18









                      spidermarnspidermarn

                      664




                      664












                      • There's also a solution without the quotes in the function call.

                        – RLave
                        Mar 8 at 9:09


















                      • There's also a solution without the quotes in the function call.

                        – RLave
                        Mar 8 at 9:09

















                      There's also a solution without the quotes in the function call.

                      – RLave
                      Mar 8 at 9:09






                      There's also a solution without the quotes in the function call.

                      – RLave
                      Mar 8 at 9:09


















                      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%2f55058084%2fpass-variables-by-name-into-a-function-that-calls-dplyr%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

                      Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                      Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                      How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page