在 R 上按列值聚合行(总和)的最简单方法是以下类型的数据框?

Which is the simplest way to aggregate rows (sum) by columns values the following type of data frame on R?

index   type.x  type.y   col3   col4
1        a        m      20      25
2        b        m      30      28
3        a        m      15      555
3        a        n      20      555
4        a        m      666     10
4        b        m      666     20

当我试图得到这个形状时,我尝试过聚合保持索引和 group_by 但没有成功:

index   col3   col4
1        20      25
2        30      28
3        35      555
4        666     30

我假设您想要第一个元素,如果它们 相似 否则 sum

library(dplyr)
df %>% 
   group_by(index) %>% 
   #n_distinct = length(unique)
   #Or using @Thomas's idea list(~sum(unique(.), na.rm = TRUE))
   summarise_at(vars(col3,col4), list(~if_else(n_distinct(.)==1, .[1], sum(., na.rm=TRUE))))

# A tibble: 4 x 3
  index  col3  col4
  <int> <int> <int>
1     1    20    25
2     2    30    28
3     3    35   555
4     4   666    30

只是假设与 A. Suliman 的 dplyr 答案中的假设类似(假设您想总结唯一值)我建议使用 data.table:

library(data.table)
my_agg_function <- function(x) {
  x <- unique(x)
  return(sum(x))
}

df[,.(col3=my_agg_function(col3),col4=my_agg_function(col4)),by=index]

如果您正在使用 base R,以下代码可能会有所帮助

r <- aggregate(df[4:5],by = df[1],function(v) sum(unique(v)))

这给出了

> r
  index col3 col4
1     1   20   25
2     2   30   28
3     3   35  555
4     4  666   30

我们也可以使用

library(dplyr)
df %>% 
  group_by(index) %>%
  summarise_at(vars(starts_with('col')), ~ sum(unique(.x)))