【问题标题】:R dplyr - get variable name as string in mutate/summariseR dplyr - 在变异/摘要中获取变量名作为字符串
【发布时间】:2017-03-08 18:47:35
【问题描述】:

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

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

任何帮助都非常感谢:)

【问题讨论】:

  • f_updated 只会产生 1 的值。看起来您只是想将组总和除以总和?如果是这样试试这个:dataset %>% dplyr::select(mpg, group) %>% mutate(tot.sum=sum(mpg)) %>% group_by(group) %>% summarise(result = sum(mpg)/mean(tot.sum))
  • 我担心我的文字有点误导,sry... sum(mpg)/sum(.$mpg) 已经成功了,但这只是一个小例子来检查我是否得到相同的输出。我的问题是,当我将变量名传递给 mutate() 中的函数时,我想将变量名作为字符串获取,但这还不能正常工作:(虽然谢谢!
  • 是的,我不知道你的实际问题是什么
  • 感谢@BWilliams 的反馈!我编辑了这个问题,希望现在更清楚了。

标签: r dplyr non-standard-evaluation


【解决方案1】:

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

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

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

【讨论】:

  • Thx,很抱歉造成混淆......我想要做的是向函数 f 传递一个列名和一个数据框在 mutate 中。我想将列名解析成一个字符串(因为 dplyr 使用非标准评估),然后用它来做 data frame[, col_name_as_string] 所以我可以使用 group_by 中的原始数据框列基本上,我想调用这个函数: f = function(col, data){ str_col = deparse(substitute(col)) sum(col)/data[,str_col] } 但不幸的是,这不起作用,因为 deparse(substitute()) 部分不是在 mutate 中返回变量名
猜你喜欢
  • 2013-08-27
  • 1970-01-01
  • 2017-08-11
  • 2015-08-23
  • 1970-01-01
  • 2020-04-28
相关资源
最近更新 更多