calculate row sum and product in data.frame

后端 未结 4 1970
一整个雨季
一整个雨季 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条回答
  •  别那么骄傲
    2020-12-18 23:50

    Only a partial answer, but if all values are greater than or equal to 0, rowSums/rowsum can be used to calculate products:

    df <- data.frame(x = c(1, 2, 5), y = c(2, 3, 1), z = c(3, 4, 2))
    
    # custom row-product-function
    my_rowprod <- function(x) exp(rowSums(log(x)))
    
    df$prod <- my_rowprod(df)
    df
    

    The generic version is (including negatives):

    my_rowprod_2 <- function(x) {
      sign <- ifelse((rowSums(x < 0) %% 2) == 1, -1, 1)
      prod <- exp(rowSums(log(abs(x)))) * sign
      prod
    }
    df$prod <- my_rowprod_2(df)
    df
    

提交回复
热议问题