Search code examples
rrowsum

How to get rowSums for selected columns in R


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.


Solution

  • Here is a quite simple solution using apply.

    output <- data.frame( x1 = apply(data[2:4], 1, sum) ,
                          x2 = apply(data[5:7], 1, sum) )
    

    result:

    output
    >    x1 x2
    > 1  14 13
    > 2  66 18
    > 3   8 12
    > 4 100 24