Search code examples
rdataframerowmedian

Add column with median absolute deviations (MADs) per row


I have the following data.frame. I would like to add a column to the left, which lists the median absolute deviations (MADs) per row (I am using the stats package). I have read posts using the rowMeans function, but I cannot use it here for the MAD. I hope someone can help, please.

 library(stats)
 df <- as.data.frame(matrix(ncol=7, nrow=3, 
    c(3,6,NA,4,5,NA,7,6,2,7,10.4,8,9,NA,3.7,4,6,0.4,NA,7,2.9), byrow = TRUE))

Solution

  • We can loop over the rows with apply, MARGIN = 1 and apply the mad

    df$MAD <- apply(df, 1, mad, na.rm = TRUE)
    df$MAD
    #[1] 1.48260 2.22390 2.29803
    

    In matrixStats, there is rowMads

    library(matrixStats)
    rowMads(as.matrix(df), na.rm = TRUE)
    #[1] 1.48260 2.22390 2.29803