首页 > 解决方案 > 如何对数据框中特定列的复制行求和?

问题描述

我有一个包含大量复制行的数据框。我想总结复制行的最后一列并同时删除复制。谁能告诉我该怎么做?示例在这里:

name <- c("a","b","c","a","c")
position <- c(192,7,6,192,99)
score <- c(1,2,3,2,5)
df <- data.frame(name,position,score)
> df
  name position score
1    a      192     1
2    b        7     2
3    c        6     3
4    a      192     2
5    c       99     5
#I would like to sum the score together if the first two columns are the 
#same. The ideal result is like this way
  name position score
1    a      192     3
2    b        7     2
3    c        6     3
4    c       99     5

衷心感谢您的帮助。

标签: rdataframe

解决方案


试试这个 :

library(dplyr)
df %>%
  group_by(name, position) %>%
  summarise(score = sum(score, na.rm = T))

推荐阅读