In R: pass column name as argument and use it in function with dplyr::mutate() and lazyeval::interp()

前端 未结 2 1653
悲哀的现实
悲哀的现实 2020-12-19 18:22

This question links to this SO answer except that here I want to use the variable specified as function arg in a mutate_(). It works if I don\'t make any \"calc

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-19 18:39

    With the devel version of dplyr (0.5.0) or in the new version (0.6.0 - awaiting release in April 2017), this can be done using slightly different syntax

    library(dplyr)
    funcN <- function(dat, varname){
     expr <- enquo(varname)
     dat %>%
         mutate(v3 = sum(!!expr))
         #or
         #mutate(v3 = sum(UQ(expr)))
    
    } 
    
    funcN(data, v1)
    #  v1 v2 v3
    #1  1  3  3
    #2  2  4  3
    

    Here, enquo takes the arguments and returns the value as a quosure (similar to substitute in base R) by evaluating the function arguments lazily and inside the summarise, we ask it to unquote (!! or UQ) so that it gets evaluated.

提交回复
热议问题