calculate row sum and product in data.frame

后端 未结 4 1959
一整个雨季
一整个雨季 2020-12-18 23:39

I would like to append a columns to my data.frame in R that contain row sums and products Consider following data frame

x    y     z
1    2     3
2    3             


        
4条回答
  •  梦毁少年i
    2020-12-19 00:09

    Try

     transform(df, sum=rowSums(df), prod=x*y*z)
     #  x y z sum prod
     #1 1 2 3   6    6
     #2 2 3 4   9   24
     #3 5 1 2   8   10
    

    Or

     transform(df, sum=rowSums(df), prod=Reduce(`*`, df))
     #   x y z sum prod
     #1 1 2 3   6    6
     #2 2 3 4   9   24
     #3 5 1 2   8   10
    

    Another option would be to use rowProds from matrixStats

     library(matrixStats)
     transform(df, sum=rowSums(df), prod=rowProds(as.matrix(df)))
    

    If you are using apply

     df[,c('sum', 'prod')] <-  t(apply(df, 1, FUN=function(x) c(sum(x), prod(x))))
     df
     #  x y z sum prod
     #1 1 2 3   6    6
     #2 2 3 4   9   24
     #3 5 1 2   8   10
    

提交回复
热议问题