I´m trying to do a column sum using apply and I would like to know if you could give me some advice to understand the best way to repete the same opperation but changing the names of the variables without having to write several lines.
I have a dataframe that looks like this but with several more variables:
a<- 100:300
b<- 50:250
c<- 200:400
d<- 0:200
e<- 300:500
df<-tibble(a,a*2, a/2, b,b*2, b/2, c,c*2, c/2, d,d*2, d/2,e,e*2, e/2)
colnames(df)<-c("A_2000", "A_2001", "A_2002", "B_2000","B_2001", "B_2002",
"C_2000","C_2001", "C_2002", "D_2000","D_2001", "D_2002",
"E_2000","E_2001", "E_2002")
This is the command I´m using to sum one set of columns:
df$A<-apply(cbind(df$A_2000,df$B_2001,df$C_2002), 1, sum)
So, my question is : is there a way to do the same for columns B, C, D and E without writing the same command 4 times? I appreciate in this case writing 4 lines is not that bad, but I have to do this for 50 different sets of variables. Appreciate the help.