Replace NA values by row means

前端 未结 3 1862
耶瑟儿~
耶瑟儿~ 2020-11-28 15:33

I want to replace my NA values from a matrix acquired by :

read.table(…)

Those values should be the mean of the corresponding row.

3条回答
  •  再見小時候
    2020-11-28 16:13

    x[is.na(x)] <- mean(x, na.rm=TRUE)  # for vectors or for a matrix as a whole
    
    t( apply(x, 1, function(xv) { xv[is.na(xv)] <- 
                                        mean(xv, na.rm=TRUE)
                                  return(xv)}
              ) ) # for a row-oriented sol'n
    

提交回复
热议问题