问题描述
我一直在尝试提取传递给dplyr :: mutate()中的函数的变量的名称,但未成功。下面是一个简短的示例,我想创建一个在mutate中返回字符串 mpg的函数:
I have been trying unsuccessfully to extract the name of a variable that was passed to a function in dplyr::mutate(). Below is a short example where I want to create a function that returns the string "mpg" inside mutate:
# 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(),因为据我所知文档仅可替代一层。当我在函数wrap()中调用f()时,它可以工作,但是当我将其放入group_by()%>%mutate()
I used lazyeval::expr_find(), because subsitute only "goes up" one layer as far as I understood the documentation. It works when I call f() inside the function wrap(), but it returns the content of mpg, instead of the name "mpg" when I put it inside group_by()%>%mutate()
我发现了一些相关的问题,但是没有一个问题可以解决我的问题。
I found some questions that are related, but none of them provided a solution to my problem.
任何帮助都非常感谢:)
Any help greatly appreciated:)
推荐答案
对于您要执行的操作,我还是不太清楚,但这也许会有所帮助:
I'm still not entirely clear on what you are trying to do, but maybe this helps:
f = function(col, data){
str_col = deparse(substitute(col))
data.frame(str_col)
}
dataset %>%
group_by(group) %>%
do(f(mpg, .))
这篇关于R dplyr-以变量/汇总形式获取变量名作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!