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

前端 未结 2 1654
悲哀的现实
悲哀的现实 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:34

    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
    

提交回复
热议问题