How to correctly use dplyr verbs inside a function definition in r?

依然范特西╮ 提交于 2019-12-05 20:08:40

Either supply character arguments and use as.name:

df.maker1 <- function(d, plant, Age){
  require(dplyr)
  dfo <- d %>% 
    filter_(lazyeval::interp(~x == 1, x = as.name(plant))) %>% 
    summarise_(age_max = lazyeval::interp(~max(x), x = as.name(Age)))
  return(dfo)
}  
df.maker1(Orange, 'Tree', 'age')
  age_max
1    1582

Or capture the arguments with substitute:

df.maker2 <- function(d, plant, Age){
  require(dplyr)
  plant <- substitute(plant)
  Age <- substitute(Age)

  dfo <- d %>% 
    filter_(lazyeval::interp(~x == 1, x = plant)) %>% 
    summarise_(age_max = lazyeval::interp(~max(x), x = Age))
  return(dfo)
}  
df.maker2(Orange, Tree, age)
  age_max
1    1582
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!