计算数据框中的相同元素r

时间:2018-04-20 11:50:23

标签: r dataframe matrix

r数据帧出现了另一个问题。

#starting position
from <- c("A","B","A","C")
to <- c("D","F","D","F")
number <- c(3,4,6,7)
data.frame(from,to,number)

如何计算两个相同“从 - 到”关系(从A到D)的数字? 结果应该看起来像我的“结果”数据框。

#result
from <- c("A","B","C")
to <- c("D","F","F")
result <- c(9,4,7)
data.frame(from,to,result)

谢谢你们:)

1 个答案:

答案 0 :(得分:2)

您可以使用group_by对“from”和“to”进行分组,然后在汇总中使用sum来获取每个组的总数。

library(dplyr)
df %>% group_by(from,to) %>% summarise(result = sum(number))