【问题标题】:Pass a concatenated string as column name in dplyr::summarise将连接的字符串作为 dplyr::summarise 中的列名传递
【发布时间】:2023-03-03 05:21:22
【问题描述】:

我正在尝试使用连接字符串作为列名迭代地执行 dplyr 汇总

Category=c("a","a","b","b","b","c","c","c")
A1=c(1,2,3,4,3,2,1,2)
A2=c(10,11,12,13,14,15,16,17)
tt=cbind(Category,A1,A2)
tdat=data.frame(tt)
colnames(tdat)=c("Category","M1","M2")
ll=matrix(1:2,nrow=2)
for(i in 1:nrow(ll)) {
  Aone=tdat %>% group_by(Category) %>%
    summarize(Msum=sum(paste("M",i,sep="")))
}

我最终出现以下错误

x invalid 'type' (character) of argument
ℹ Input Msum is sum(paste("M", i, sep = "")).
ℹ The error occurred in group 1: Category = "A".
Run rlang::last_error() to see where the error occurred.```


The goal is to iteratively get arithmentic functions within summarize function in dplyr. But this concatenated string is not recognized as column name. 

【问题讨论】:

  • 您的代码返回错误Error in cbind(Category, A1, A2) : object 'Category' not found。当您执行cbind(Category,A1,A2) 时,也没有定义A1A2。您能否更正代码以使您的帖子可重现?如果您显示共享数据的预期输出也会很有帮助。
  • Category 列是什么。
  • 刚刚更新了代码
  • 我更新了帖子。它对我有用

标签: r dplyr concatenation paste summarize


【解决方案1】:

如果我们想传递一个字符串作为列名,则转换为symbol 并计算 (!!)

library(dplyr)
Aone <- vector('list', nrow(ll))
for(i in seq_len(nrow(ll))) {
      Aone[[i]] <- tdat %>%
                    group_by(Category) %>%
                    summarize(Msum = sum(!! rlang::sym(paste("M", i, sep=""))))
    }

或者假设列名是“M-1”、“M-2”等,它应该也可以工作

Aone <- vector('list', 2)
for(i in seq_along(Aone)) {
   Aone[[i]] <- tdat %>%
        group_by(Category) %>% 
       summarise(Msum = sum(!! rlang::sym(paste("M-", i, sep=""))), 
         .groups = 'drop')
  }

注意:ll 在原帖中并不清楚。在这里,我们创建一个list,其中length 等于“M-”列的数量,并通过循环该list 的序列将输出分配回list 元素

数据

tdat <- data.frame(Category, M1, M2)


tdat <- structure(list(Category = c("A", "A", "A", "A", "B", "B", "B", 
"B"), `M-1` = c(1, 2, 3, 4, 3, 2, 1, 2), `M-2` = c(10, 11, 12, 
13, 14, 15, 16, 17)), class = "data.frame", row.names = c(NA, 
-8L))

【讨论】:

  • 谢谢@akrun!这有帮助。如果变量名中包含连字符,这将如何变化?
  • @Vignesh 如果是M_1M_2等则把paste改成paste("M_", i, ..
  • 如果是 M-1, M-2 --> 我试过 !!rlang::sym(paste("`M-",i,"`",sep="")) 并显示错误。
  • 如果它是非常规名称,即-,您可以在评估时使用`反引号
  • 我用反引号编辑了之前的评论。
猜你喜欢
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2018-06-21
相关资源
最近更新 更多