dplyr - using mutate() like rowmeans()

前端 未结 6 1688
后悔当初
后悔当初 2020-12-01 07:55

I can\'t find the answer anywhere.

I would like to calculate new variable of data frame which is based on mean of rows.

For example:

data &l         


        
6条回答
  •  感情败类
    2020-12-01 08:26

    You're looking for

    data %>% 
        rowwise() %>% 
        mutate(c=mean(c(a,b)))
    
    #      id     a     b     c
    #   (dbl) (dbl) (dbl) (dbl)
    # 1   101     1     2   1.5
    # 2   102     2     2   2.0
    # 3   103     3     2   2.5
    

    or

    library(purrr)
    data %>% 
        rowwise() %>% 
        mutate(c=lift_vd(mean)(a,b))
    

提交回复
热议问题