-2

I have a data set where i need to obtain sum of various variables by grouping it by a variable in R. The data set is as follows:

V1 V2 V3 V4
1  2   3 a
5  6   7 a
3  2   3 b
5  6   7 b

I want the output in the form:

V1 V2 V3 V4
6  8  10  a
8  8  10  b

I want to use a loop for doing this. It will be great if someone can help

ArunK
  • 1,731
  • 16
  • 35

1 Answers1

0

you can use dplyr library do that

library("dplyr")
df <- data.frame(V1 = c(1,5,3,5), V2 = c(2,6,2,6), V3 = c(3,7,3,7), V4 = c("a","a","b","b")
res_df <- df %>% group_by(V4) %>% summarise(V1=sum(V1),V2=sum(V2),V3=sum(V3))
ArunK
  • 1,731
  • 16
  • 35