问题
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.
回答1:
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
回答2:
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
回答3:
OK, if you want a separate dataframe:
> data.frame(X1=rowSums(data[,2:4]), X2=rowSums(data[,5:7]))
回答4:
rowSums(cbind(mydata$variable1, mydata$variable2, mydata$variable3), na.rm = T )
回答5:
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
回答6:
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
来源:https://stackoverflow.com/questions/37085389/how-to-get-rowsums-for-selected-columns-in-r