【发布时间】: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)时,也没有定义A1、A2。您能否更正代码以使您的帖子可重现?如果您显示共享数据的预期输出也会很有帮助。 -
Category列是什么。 -
刚刚更新了代码
-
我更新了帖子。它对我有用
标签: r dplyr concatenation paste summarize