How to pass dynamic column names in dplyr into custom function?

前端 未结 1 1266
野的像风
野的像风 2020-12-05 05:08

I have a dataset with the following structure:

Classes ‘tbl_df’ and \'data.frame\':  10 obs. of  7 variables:
 $ GdeName  : chr  \"Aeugst am Albis\" \"Aeugst         


        
相关标签:
1条回答
  • 2020-12-05 05:37

    Using the latest version of dplyr (>=0.7), you can use the rlang !! (bang-bang) operator.

    library(tidyverse)
    from <- "Stand1971"
    to <- "Stand1987"
    
    data %>%
      mutate(diff=(!!as.name(from))-(!!as.name(to)))
    

    You just need to convert the strings to names with as.name and then insert them into the expression. Unfortunately I seem to have to use a few more parenthesis than I would like, but the !! operator seems to fall in a weird order-of-operations order.

    Original answer, dplyr (0.3-<0.7):

    From that vignette (vignette("nse","dplyr")), use lazyeval's interp() function

    library(lazyeval)
    
    from <- "Stand1971"
    to <- "Stand1987"
    
    data %>%
      mutate_(diff=interp(~from - to, from=as.name(from), to=as.name(to)))
    
    0 讨论(0)
提交回复
热议问题