-1

I have a data frame like this:

V1   V2  V3
AAA  x   2
AAA  x   5
AAA  y   7
BBB  y   7
BBB  x   8
BBB  y   3

I would like to sum up the values from V3 depending on V1 and get a data frame like that:

V1   V2  V3
AAA  x   7
AAA  y   7
BBB  x   8
BBB  y   10

Thanks for your help!

Nina W.
  • 13
  • 2
  • 1
    Try `aggregate(V3 ~ ., df1, sum)` or `library(dplyr); df1 %>% group_by(V1, V2) %>% summarise(V3 = sum(V3))` – akrun Aug 29 '18 at 14:29

2 Answers2

1

Use sqldf. Group by v1,v2 and do the sum(v3) as follow:

library(sqldf)
sqldf("select V1,V2,sum(V3) from df group by V1,V2")

Output:

    V1 V2 sum(V3)
1 AAA  x       7
2 AAA  y       7
3 BBB  x       8
4 BBB  y      10
Saurabh Chauhan
  • 3,161
  • 2
  • 19
  • 46
0

The dataset

dt <- data.frame(V1=c("AAA","AAA","AAA","BBB","BBB","BBB"),
                 V2=c("x","x","y","y","x","y"),
                 V3=c(2,5,7,7,8,3))
dt

The code:

library(tidyverse)

dt %>%
  group_by(V1,V2) %>%
  mutate( Sum= sum(V3))
Sal-laS
  • 11,016
  • 25
  • 99
  • 169