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

R dplyr-在mutate/summary中将变量名作为字符串获取,r,dplyr,non-standard-evaluation,R,Dplyr,Non Standard Evaluation,我一直试图提取传递给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(la

我一直试图提取传递给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(),因为就我对文档的理解而言,substitute只“上升”了一层。当我在函数wrap()中调用f()时,它会工作,但当我将其放入group_by()%>%mutate()时,它会返回mpg的内容,而不是名称“mpg”

我发现了一些相关的问题,但没有一个能解决我的问题


非常感谢您的帮助:)

我还不完全清楚您想做什么,但这可能会有帮助:

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

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

f_updated只会产生一个值1。看起来你只是想把组和除以总和?如果是这样,请尝试以下操作:
dataset%%>%dplyr::select(mpg,group)%%>%mutate(tot.sum=sum(mpg))%%>%groupby(group)%%>%summary(result=sum(mpg)/mean(tot.sum))
我担心我的文字有点误导,sry。。。sum(mpg)/sum(.$mpg)已经做到了这一点,但这只是检查我是否得到相同输出的一个小示例。我的问题是,当我将变量名传递给mutate()中的函数时,我希望将其作为字符串获取,但这还不起作用:(thx!是的,我不知道你的实际问题是什么,谢谢你的反馈!我编辑了这个问题,希望它现在更清楚。thx,很抱歉混淆了…我想做的是在mutate中传递函数f一个列名和一个数据框。我想把列名解析成一个字符串(因为dplyr使用非标准求值),然后使用它来执行数据帧[,col_name_as_string],所以我可以使用组_中的原始数据帧列,基本上,我想调用这个函数:f=函数(col,data){str_col=deparse(substitute(col))sum(col)/data[,str_col]}但不幸的是,这不起作用,因为deparse(substitute())部分没有返回mutate中的变量名