R dplyr - 在 mutate/summarise 中获取变量名称作为字符串

R dplyr - get variable name as string in mutate/summarise

提问人:Christoph 提问时间:3/9/2017 最后编辑:Christoph 更新时间:3/11/2017 访问量:1371

问:

我一直在尝试提取传递给 dplyr::mutate() 中函数的变量的名称,但没有成功。下面是一个简短的示例,我想创建一个函数,在 mutate 中返回字符串“mpg”:

# mtcars dataset with grouping variable
dataset = mtcars
dataset$group = c(1, 2, 3, 4)

# function to call inside mutate()
f = function(col, data){
  str_col = deparse(lazyeval::expr_find(col))
  str_col
}

# this does not work: returns the content of mpg 
# instead of the variable name as a string
dataset %>%
  group_by(group) %>%
  mutate(f = f(mpg, dataset)
  ) %>%
  select(group, f)

我使用了 lazyeval::expr_find(),因为据我所知,subsitute 只“上升”了一层。当我在函数 wrap() 中调用 f() 时它起作用,但是当我将其放入 group_by()%>%mutate() 中时,它返回 mpg 的内容,而不是名称“mpg”

我发现了一些相关的问题,但没有一个能为我的问题提供解决方案。

任何帮助,非常感谢:)

R DPLYR 非标准评估

评论

1赞 B Williams 3/9/2017
f_updated 只会产生值 1。看起来您只是想将组总和除以总和?如果是这样,请尝试以下操作:dataset %>% dplyr::select(mpg, group) %>% mutate(tot.sum=sum(mpg)) %>% group_by(group) %>% summarise(result = sum(mpg)/mean(tot.sum))
0赞 Christoph 3/10/2017
我担心我的文字有点误导,令人毛骨悚然......sum(mpg)/sum(.$mpg) 已经可以解决问题,但这只是一个小例子,用于检查我是否得到相同的输出。我的问题是,当我将变量名称传递给 mutate() 中的函数时,我想将变量名称作为字符串获取,但这还不起作用:( 谢谢!
1赞 B Williams 3/10/2017
是的,我不知道你的实际问题是什么
0赞 Christoph 3/11/2017
感谢您@BWilliams反馈!我编辑了这个问题,希望现在更清楚了。

答:

1赞 B Williams 3/11/2017 #1

我仍然不完全清楚你想做什么,但也许这会有所帮助:

f = function(col, data){
  str_col = deparse(substitute(col))
  data.frame(str_col)
}

dataset %>% 
   group_by(group) %>% 
   do(f(mpg, .))

评论

0赞 Christoph 3/13/2017
谢谢,很抱歉造成混乱......我想做的是在 mutate 中传递函数 f 列名和数据帧。我想将列名解析为字符串(因为 dplyr 使用非标准评估),然后用它来执行数据帧[, col_name_as_string],这样我就可以在 group_by 中使用原始数据框列 基本上,我想调用这个函数: f = function(col, data){ str_col = deparse(substitute(col)) sum(col)/data[,str_col] } 但不幸的是,这不起作用,因为 deparse(substitute()) 部分没有返回 mutate 中的变量名称