Replace NA values by row means

前端 未结 3 1844
耶瑟儿~
耶瑟儿~ 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
    
    0 讨论(0)
  • 2020-11-28 16:20
    a = c(NA, 1, 2, 3, 10)
    a[which(is.na(a)==TRUE)] = mean(a,na.rm = T)
    
    0 讨论(0)
  • 2020-11-28 16:25

    Here's some sample data.

    m <- matrix(1:16, nrow=4)
    m[c(1,4,6,11,16)] <- NA
    

    And here's how I'd fill in missings with the row means.

    k <- which(is.na(m), arr.ind=TRUE)
    m[k] <- rowMeans(m, na.rm=TRUE)[k[,1]]
    

    Your data will be in a data.frame; you'll have to convert to a matrix first using as.matrix. You may or may not want to leave it in that format; to convert back use as.data.frame.

    0 讨论(0)
提交回复
热议问题