提问人:Christoph 提问时间:3/9/2017 最后编辑:Christoph 更新时间:3/11/2017 访问量:1371
R dplyr - 在 mutate/summarise 中获取变量名称作为字符串
R dplyr - get variable name as string in mutate/summarise
问:
我一直在尝试提取传递给 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”
我发现了一些相关的问题,但没有一个能为我的问题提供解决方案。
任何帮助,非常感谢:)
答:
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 中的变量名称
评论
dataset %>% dplyr::select(mpg, group) %>% mutate(tot.sum=sum(mpg)) %>% group_by(group) %>% summarise(result = sum(mpg)/mean(tot.sum))