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

混江龙づ霸主 提交于 2019-11-29 12:09:13

You have to use lazy evaluation (with the package lazyeval), for example like this:

library(lazyeval)
func2 <- function(df, varname){
     df %>%
       mutate_(v3=interp(~sum(x), x = as.name(varname)))
}
func2(data, "v1")
#  v1 v2 v3
#1  1  3  3
#2  2  4  3

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!