0

got another problem with r dataframes.

#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)

How can I count the numbers of the two same "from-to" relations (from A to D)? The result should look like my "result" dataframe.

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

Thank you guys :)

meilirog
  • 15
  • 1
  • 4
  • 1
    Many ways `library(dplyr);df %>% group_by(from, to) %>% summarise(result = sum(number))` or `aggregate(number ~ ., df, sum)` – akrun Apr 20 '18 at 11:52

1 Answers1

2

You can use group_by to group "from" and "to" then use sum in summarise to get the total for each of the groups.

library(dplyr)
df %>% group_by(from,to) %>% summarise(result = sum(number))
jasbner
  • 2,253
  • 12
  • 24