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\"
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
OK, if you want a separate dataframe:
> data.frame(X1=rowSums(data[,2:4]), X2=rowSums(data[,5:7]))
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
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
rowSums(cbind(mydata$variable1, mydata$variable2, mydata$variable3), na.rm = T )
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