根据行值执行colsum

时间:2018-02-17 19:23:51

标签: r

嗨我有3个数据集,包含项目和计数。我需要添加所有数据集并根据项目名称组合计数。他是我的投入。

Df1 <- data.frame(items =c("Cookies", "Candys","Toys","Games"), Counts = c( 10,20,30,5))
Df2 <- data.frame(items =c( "Candys","Cookies","Toys"), Counts = c( 5,21,20))
Df3 <- data.frame(items =c( "Playdows","Gummies","Candys"), Counts = c(10,15,20))
Df_all <- rbind(Df1,Df2,Df3)
  

Df_all

      items Counts
1   Cookies     10
2    Candys     20
3      Toys     30
4     Games      5
5    Candys      5
6   Cookies     21
7      Toys     20
8  Playdows     10
9   Gummies     15
10   Candys     20

我需要根据项目值组合列。添加值后删除行。我的输出应该是

    items   Counts
1   Cookies     31
2    Candys     45
3      Toys     50
4     Games      5
5  Playdows     10
6   Gummies     15

你能帮忙在r。

中获得这个输出

2 个答案:

答案 0 :(得分:0)

使用dplyr:

    library(dplyr)
    result<-Df_all%>%group_by(items)%>%summarize(sum(Counts))
    > result
# A tibble: 6 x 2
  items    `sum(Counts)`
  <fct>            <dbl>
1 Candys           45.0 
2 Cookies          31.0 
3 Games             5.00
4 Toys             50.0 
5 Gummies          15.0 
6 Playdows         10.0   

答案 1 :(得分:0)

您可以使用tapply

tapply(Df_all$Counts, Df_all$items, FUN=sum)

返回什么

  Candys  Cookies    Games     Toys  Gummies Playdows 
      45       31        5       50       15       10