How to get rowSums for selected columns in R

sriya picture sriya · May 7, 2016 · Viewed 27.5k times · Source

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.

Answer

Technophobe01 picture Technophobe01 · May 7, 2016

My sense would be to use dply:

require(dply)
data %>% mutate(v2v4 = rowSums(.[2:4])) %>% mutate(v4v6 = rowSums(.[5:7])) %>% select(-(location:v6))

result:

> newDf <- data %>% mutate(v2v4 = rowSums(.[2:4])) %>% mutate(v4v6 = rowSums(.[5:7])) %>% select(-(location:v6))
> newDf
  v2v4 v4v6
1   14   13
2   66   18
3    8   12
4  100   24