How to get the average of two columns using dplyr?

Carter picture Carter · Dec 9, 2015 · Viewed 15.7k times · Source

how to get the average of two columns of a data table using dplyr? For example, if my data if like below:

dt <- data.table(A=1:5, B=c(1,4,NA,6,8))

I want to create a new column "Avg" which is the mean of column A and B for each row:

dt %>% mutate(Avg=mean(c(A, B), na.rm=T))

But this code does not give me the correct result. How to do this? Thank you very much.

Answer

Stedy picture Stedy · Dec 9, 2015

If you want to use dplyr to achieve this, I would suggest using the function rowwise():

    R> library(dplyr)
    R> dt <- data.table(A=1:5, B=c(1,4,NA,6,8))
    R> j <- dt %>% rowwise() %>% mutate(Avg=mean(c(A, B), na.rm=T)) 
    R> j
Source: local data frame [5 x 3]
Groups: <by row>

      A     B   Avg
  (int) (dbl) (dbl)
1     1     1   1.0
2     2     4   3.0
3     3    NA   3.0
4     4     6   5.0
5     5     8   6.5