简体   繁体   中英

Summing data based on Column in R

I have a data set that looks like this (actual data is 10K by 5K so I really need a shortcut):

Cluster Item1 Item2 Item 3
1 1 2 2
1 3 1 1
1 1 3 0
2 3 2 0
2 0 0 2
2 4 2 2
3 0 1 1
3 1 1 2

I want to add the columns of each data set by cluster so it will look I this:

Cluster Item1 Item2 Item 3
1 5 6 3
2 7 4 4
3 1 2 3

I want to sum them by a certain column.

You can use aggregate ( dat is the name of your data frame):

aggregate(dat[-1], dat["Cluster"], sum)

#   Cluster Item1 Item2 Item3
# 1       1     5     6     3
# 2       2     7     4     4
# 3       3     1     2     3

With data.table :

library(data.table)
setDT(dat)[ , lapply(.SD, sum), by = Cluster]
#    Cluster Item1 Item2 Item3
# 1:       1     5     6     3
# 2:       2     7     4     4
# 3:       3     1     2     3

With dplyr :

dat %>%
  group_by(Cluster) %>%
  summarise_each(funs(sum))
#   Cluster Item1 Item2 Item3
# 1       1     5     6     3
# 2       2     7     4     4
# 3       3     1     2     3

thanks for your answer, I also used this good and it worked perfectly:

 aggregate(. ~ Cluster, data=dat, FUN=sum)



#   Cluster Item1 Item2 Item3
# 1       1     5     6     3
# 2       2     7     4     4
# 3       3     1     2     3

Try:

> sapply(ddf[-1], function(x) tapply(x,ddf$Cluster,sum))
  Item1 Item2 Item3
1     5     6     3
2     7     4     4
3     1     2     3

If you want to sum all varibales except that of grouping, use across in dplyr

df <- read.table(text = "Cluster    Item1   Item2   Item3
1   1   2   2
1   3   1   1
1   1   3   0
2   3   2   0
2   0   0   2
2   4   2   2
3   0   1   1
3   1   1   2", header = T)

df %>% group_by(Cluster) %>% summarise(across(everything(), ~sum(.)))

# A tibble: 3 x 4
  Cluster Item1 Item2 Item3
    <int> <int> <int> <int>
1       1     5     6     3
2       2     7     4     4
3       3     1     2     3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM