I am a newbie to R and seek help to calculate sums of selected column for each row. My simple data frame is as below.
data = data.frame(location = c("a","b","c","d"),
v1 = c(3,4,3,3), v2 = c(4,56,3,88), v3 =c(7,6,2,9), v4=c(7,6,1,9),
v5 =c(4,4,7,9), v6 = c(2,8,4,6))
I want sum of columns V1 to V3 and V4 to V6 for my each row in a new data frame.
x1 x2
a 14 13
b 66 18
c
d
I did something like below.
rowSums(data[,2:4][,5:7])
But something should be wrong in my codes. Thanks in advance for any help.
Here is a quite simple solution using
apply
.result:
OK, if you want a separate dataframe:
My sense would be to use dply:
result:
We can
split
the dataset into alist
and then useReduce
withf="+"
.Specifying the two summations explicitly: