【问题标题】:R - dplyr 0.4.1 : How to summarise by a column name in a functionR - dplyr 0.4.1:如何通过函数中的列名进行汇总
【发布时间】:2018-12-17 15:47:23
【问题描述】:

我需要创建一个函数,该函数可以group_bysummarise 使用其名称的数据框列。 我正在使用 dplyr 版本 0.4.1(我无法更新),所以看起来我在其他主题上找到的解决方案不起作用......

这是我的例子:

data <- data.frame(section=rep(c("A","B"),3), quantity=c(6:11))
#I need to get this result : 
RESULT = data %>% group_by(section) %>% summarise(total=sum(quantity))

我实现了这个功能,但出现错误:

# function : 
synthetize = function(x,column,measure){
  result = x %>% group_by(column) %>% summarise(total=sum(measure))
}
RESULT2=synthetize(data,column="section",measure="quantity")
RESULT2

我试过evalget,但似乎没有帮助

【问题讨论】:

  • 你的R是什么版本?
  • 我目前正在使用 R 3.2.0

标签: r dplyr


【解决方案1】:

我们可以使用rlang::sym 将字符串转换为符号并计算 (!!)

library(tidyverse)
synthetize = function(x, column, measure){
     x %>% 
        group_by_at(column) %>%
        summarise(total=sum(!! rlang::sym(measure)))
   }

synthetize(data, column="section", measure="quantity")
# A tibble: 2 x 2
#  section total
#   <fct>   <int>
#1 A          24
#2 B          27

注意:这里我们使用 OP 的相同参数类型


如果我们使用的是旧版本的dplyr,以下可能会有所帮助

library(lazyeval)
synthetize2 = function(x, column, measure){

  x %>% 
     group_by_(column) %>%
     summarise(total = interp(~ sum(v1), v1 = as.name(measure)))


synthetize2(data, column='section', measure='quantity')

【讨论】:

  • 感谢您的回复。我也不能使用 tidyverse... 所以我收到一条错误消息:Error in function_list[[i]](value) : impossible de trouver la fonction "group_by_at"
  • 确实,我使用的是旧版本的dplyr。不过,看起来interp() 并没有解决问题:Error in eval(substitute(expr), envir, enclos) : Not a vector
【解决方案2】:

另一种方法是enquo:

library(tidyverse)

synthetize = function(x,column,measure) {

  result = x %>% group_by(!! enquo(column)) %>% summarise(total := sum(!! enquo(measure)))

}

在这种情况下,您不需要引用变量:

RESULT2 = synthetize(data, column = section, measure = quantity)

RESULT2

# A tibble: 2 x 2
  section total
  <fct>   <int>
1 A          24
2 B          27

如果您无法访问最新的tidyverse,请尝试使用get

library(dplyr)

synthetize = function(x,column,measure) {

  result = x %>% group_by(get(column)) %>% summarise(total := sum(get(measure)))

}

【讨论】:

  • 谢谢。不幸的是,它不起作用(由于 dplyr 的 0.4.1 版本,我猜......):Error in mutate_impl(.data, dots) : objet 'section' introuvable
  • 试试我刚刚添加的方法。在这种情况下,您需要引用参数。
  • 再次感谢! get 解决方案不能解决问题...:Error in get("section") : objet 'section' introuvable
  • 嗯,那可能是因为之前的版本。不幸的是,我无法轻松降级和测试。
猜你喜欢
  • 2021-10-01
  • 2021-01-19
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 2016-11-30
  • 2020-01-10
  • 1970-01-01
相关资源
最近更新 更多