R 如何在数据框的所有列上应用函数

R 如何在数据框的所有列上应用函数,r,dataframe,apply,R,Dataframe,Apply,我有一个如下所示的数据帧: a b c d e 1 2 3 1 1 2 3 0 1 1 3 4 2 1 1 4 5 0 1 2 5 0 7 1 2 我想为列e中的每个唯一值对每列求和。 因此,我的输出应该是: a b c d e 6 9 5 3 1 9 5 7 2 2 我该怎么做?使用by cbind(do.call(rbind, by(d[-5], d$e, colSums)), e=unique(d$e)) # a b c d e # 1 6 9 5 3 1 # 2 9 5 7

我有一个如下所示的数据帧:

a b c d e
1 2 3 1 1
2 3 0 1 1 
3 4 2 1 1
4 5 0 1 2
5 0 7 1 2
我想为列
e
中的每个唯一值对每列求和。 因此,我的输出应该是:

a b c d e
6 9 5 3 1
9 5 7 2 2 
我该怎么做?

使用
by

cbind(do.call(rbind, by(d[-5], d$e, colSums)), e=unique(d$e))
#   a b c d e
# 1 6 9 5 3 1
# 2 9 5 7 2 2
或者使用
aggregate

aggregate(. ~ e, d, FUN=sum)
#   e a b c d
# 1 1 6 9 5 3
# 2 2 9 5 7 2
数据


d您要按组进行总结。您可以这样做:
library(dplyr);数据%>%(e)%%>%汇总(总和)
d <- structure(list(a = 1:5, b = c(2L, 3L, 4L, 5L, 0L), c = c(3L, 
0L, 2L, 0L, 7L), d = c(1L, 1L, 1L, 1L, 1L), e = c(1L, 1L, 1L, 
2L, 2L)), row.names = c(NA, -5L), class = "data.frame")