在R中汇总聚合内的列

我知道我可以在汇总数据后重新命名列:

blubb <- aggregate(dat$two ~ dat$one, ...) colnames(blubb) <- c("One", "Two") 

没有错。 但是有没有办法一次性聚合和命名列? 有点像:

 blubb <- aggregate( ... , cols = c("One", "Two")) 

这将是escpecially很好(和错字),以某种方式赶上原来的列名,并做如下:

 blubb <- aggregate( ... , cols = c(name_of_dat$one, name_of_dat$two."_Mean")) 

你可以像下面这样使用setNames

 blubb <- setNames(aggregate(dat$two ~ dat$one, ...), c("One", "Two")) 

或者,您可以绕过光滑的公式方法,并使用如下语法:

 blubb <- aggregate(list(One = dat$one), list(Two = dat$two), ...) 

更新

此更新只是帮助您开始自行获得解决scheme。

如果你检查stats:::aggregate.formula的代码,你会看到最后的几行:

 if (is.matrix(mf[[1L]])) { lhs <- as.data.frame(mf[[1L]]) names(lhs) <- as.character(m[[2L]][[2L]])[-1L] aggregate.data.frame(lhs, mf[-1L], FUN = FUN, ...) } else aggregate.data.frame(mf[1L], mf[-1L], FUN = FUN, ...) 

如果你想要做的只是把函数名追加到被聚合的variables上,也许你可以把它改成:

 if (is.matrix(mf[[1L]])) { lhs <- as.data.frame(mf[[1L]]) names(lhs) <- as.character(m[[2L]][[2L]])[-1L] myOut <- aggregate.data.frame(lhs, mf[-1L], FUN = FUN, ...) colnames(myOut) <- c(names(mf[-1L]), paste(names(lhs), deparse(substitute(FUN)), sep = ".")) } else { myOut <- aggregate.data.frame(mf[1L], mf[-1L], FUN = FUN, ...) colnames(myOut) <- c(names(mf[-1L]), paste(strsplit(gsub("cbind\\(|\\)|\\s", "", names(mf[1L])), ",")[[1]], deparse(substitute(FUN)), sep = ".")) } myOut 

这基本上是通过使用deparse(substitute(FUN))来捕获为FUNinput的值,所以你可以修改函数来接受一个自定义的后缀,或者甚至可以是一个后缀向量。 有些工作可能会改善一点,但我不打算这样做!

这是应用这个概念的Gist ,创build一个名为“myAgg”的函数。

以下是结果列名的一些示例输出:

 > names(myAgg(weight ~ feed, data = chickwts, mean)) [1] "feed" "weight.mean" > names(myAgg(breaks ~ wool + tension, data = warpbreaks, sum)) [1] "wool" "tension" "breaks.sum" > names(myAgg(weight ~ feed, data = chickwts, FUN = function(x) mean(x^2))) [1] "feed" "weight.function(x) mean(x^2)" 

请注意,只有聚合的variables名称发生更改。 但是请注意,如果您使用自定义函数,则最终会出现一个非常奇怪的列名!

你的第一个问题的答案是肯定的。 您当然可以在集合函数中包含列名称。 使用上面例子中的名字:

blubb <- aggregate(dat,list(One=dat$One,Two=dat$Two),sum)

我喜欢可能自动拉入原始列名的部分。 如果我知道了,我会发布它。

 w <- data.frame(Funding<-"Fully Insured",Region="North East",claim_count=rnbinom(1000, 300.503572818, mu= 0.5739467)) x <- data.frame(Funding<-"Fully Insured",Region="South East",claim_count=rnbinom(1000, 1000, mu= 0.70000000)) y <- data.frame(Funding<-"Self Insured",Region="North East",claim_count=rnbinom(1000, 400, mu= 0.80000000)) z <- data.frame(Funding<-"Self Insured",Region="South East",claim_count=rnbinom(1000, 700, mu= 1.70000000)) names(w)<-c("Funding","Region","claim_count") names(x)<-c("Funding","Region","claim_count") names(y)<-c("Funding","Region","claim_count") names(z)<-c("Funding","Region","claim_count") my_df <- rbind(w,x,y,z) my_df2<-with(my_df, aggregate(x=claim_count, by=list(Funding,Region), FUN=sum)) colnames(my_df2)<-colnames(my_df)