How to get rowSums for selected columns in R

前端 未结 6 397
余生分开走
余生分开走 2021-01-27 19:30

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\"         


        
相关标签:
6条回答
  • 2021-01-27 20:01

    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
    
    0 讨论(0)
  • 2021-01-27 20:02

    OK, if you want a separate dataframe:

    > data.frame(X1=rowSums(data[,2:4]), X2=rowSums(data[,5:7]))
    
    0 讨论(0)
  • 2021-01-27 20:05

    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
    
    0 讨论(0)
  • 2021-01-27 20:11

    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
    
    0 讨论(0)
  • 2021-01-27 20:11
    rowSums(cbind(mydata$variable1, mydata$variable2, mydata$variable3), na.rm = T )
    
    0 讨论(0)
  • 2021-01-27 20:20

    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
    
    0 讨论(0)
提交回复
热议问题