dplyr - using mutate() like rowmeans()

前端 未结 6 1683
后悔当初
后悔当初 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条回答
  •  猫巷女王i
    2020-12-01 08:26

    Another simple possibility with few code is:

    data %>%
        mutate(c= rowMeans(data.frame(a,b)))
    
     #     id a b   c
     #  1 101 1 2 1.5
     #  2 102 2 2 2.0
     #  3 103 3 2 2.5
    

    As rowMeans needs something like a matrix or a data.frame, you can use data.frame(var1, var2, ...) instead of c(var1, var2, ...). If you have NAs in your data you'll need to tell R what to do, for example to remove them: rowMeans(data.frame(a,b), na.rm=TRUE)

提交回复
热议问题