How to impute missing values with row mean in R

前端 未结 2 417
孤独总比滥情好
孤独总比滥情好 2021-01-19 06:53

From a large data frame, I have extracted a row of numeric data and saved as a vector. Some of the values are missing and marked as NA. I want to impute the missing values w

相关标签:
2条回答
  • 2021-01-19 07:20

    Use this:

    filter <- is.na(myVec)
    
    myVec[filter] <- colMeans(myDF[,filter], na.rm=TRUE)
    

    Where myVec is your vector and myDF is your data.frame.

    0 讨论(0)
  • 2021-01-19 07:25

    Let x be your vector:

    x <- c(NA,0,2,0,2,NA,NA,NA,0,2)
    ifelse(is.na(x), mean(x, na.rm = TRUE), x)
    # [1] 1 0 2 0 2 1 1 1 0 2
    

    Or if you don't care for the original vector, you can modify it directly:

    x[is.na(x)] <- mean(x, na.rm = TRUE)
    
    0 讨论(0)
提交回复
热议问题