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

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived