How to get rowSums for selected columns in R

2020-05-08 07:01发布

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.

标签: r rowsum
6条回答
Bombasti
2楼-- · 2020-05-08 07:16

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
查看更多
趁早两清
3楼-- · 2020-05-08 07:17
rowSums(cbind(mydata$variable1, mydata$variable2, mydata$variable3), na.rm = T )
查看更多
一纸荒年 Trace。
4楼-- · 2020-05-08 07:21

OK, if you want a separate dataframe:

> data.frame(X1=rowSums(data[,2:4]), X2=rowSums(data[,5:7]))
查看更多
混吃等死
5楼-- · 2020-05-08 07:29

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
查看更多
Explosion°爆炸
6楼-- · 2020-05-08 07:39

We can split the dataset into a list and then use Reduce with f="+".

sapply(split.default(data[-1], rep(paste0("x", 1:2), each=3)), Reduce, f=`+`)
#     x1 x2
#[1,]  14 13
#[2,]  66 18
#[3,]   8 12
#[4,] 100 24
查看更多
Emotional °昔
7楼-- · 2020-05-08 07:42

Specifying the two summations explicitly:

cbind(x1=rowSums(data[,c('v1','v2','v3')]),x2=rowSums(data[,c('v4','v5','v6')]));
##       x1 x2
## [1,]  14 13
## [2,]  66 18
## [3,]   8 12
## [4,] 100 24
查看更多
登录 后发表回答