r按相同名称分组的总和

时间:2018-10-05 03:16:36

标签: r

有没有办法在r中没有循环的情况下求和这些数据? 第一行中没有NA或空白。 这是顺序数据的列表。

之前:

Column 1  Column 2
FLOWING 
DOWNTIME  1,922
FLOWING   23
FLOWING   8
FLOWING   23
FLOWING   26
DOWNTIME  36
FLOWING   1
FLOWING   8
DOWNTIME  12
FLOWING   0
FLOWING   3
FLOWING   13
DOWNTIME  2
FLOWING   10
FLOWING   12
FLOWING   30
DOWNTIME  24
DOWNTIME  1

之后:

Column 1  Column 2
FLOWING 
DOWNTIME  1,922
FLOWING   80
DOWNTIME  36
FLOWING   9
DOWNTIME  12
FLOWING   16
DOWNTIME  2
FLOWING   52
DOWNTIME  25

1 个答案:

答案 0 :(得分:2)

“ Column2”中有,,这使其成为character类。因此,我们将,转换为numeric并按'Column1'的运行长度ID(sum中的rleid分组后得到data.table

library(dplyr)
library(data.table)
df1 %>%
    mutate(Column2 = as.numeric(str_remove(Column2, ","))) %>%
    group_by(grp = rleid(Column1)) %>% 
    summarise(Column1 = first(Column1), 
              Column2 = sum(Column2)) %>%
    ungroup %>%
    select(-grp)

或使用data.table方法

setDT(df1)[, .(Column1 = first(Column1), 
      Column2 = sum(as.numeric(sub(",", "", Column2)))), .(grp = rleid(Column1))]

数据

df1 <- structure(list(Column1 = c("FLOWING", "DOWNTIME", "FLOWING", 
 "FLOWING", "FLOWING", "FLOWING", "DOWNTIME", "FLOWING", "FLOWING", 
 "DOWNTIME", "FLOWING", "FLOWING", "FLOWING", "DOWNTIME", "FLOWING", 
 "FLOWING", "FLOWING", "DOWNTIME", "DOWNTIME"), Column2 = c("", 
 "1,922", "23", "8", "23", "26", "36", "1", "8", "12", "0", "3", 
 "13", "2", "10", "12", "30", "24", "1")), class = "data.frame", 
 row.names = c(NA, -19L))