Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rowSums for selected columns in R

Tags:

r

rowsum

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.

like image 734
sriya Avatar asked Dec 05 '22 00:12

sriya


2 Answers

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
like image 158
Technophobe01 Avatar answered Dec 06 '22 14:12

Technophobe01


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
like image 25
rafa.pereira Avatar answered Dec 06 '22 14:12

rafa.pereira