mean-before-after imputation in R

前端 未结 4 823
渐次进展
渐次进展 2021-01-21 11:03

I\'m new in R. My question is how to impute missing value using mean of before and after of the missing data point?

example;

using the mean from the upper and lo

4条回答
  •  醉话见心
    2021-01-21 11:23

    This would be a basic manual approach you can take:

    age <- c(52, 27, NA, 23, 39, 32, NA, 33, 43)
    age[is.na(age)] <- rowMeans(cbind(age[which(is.na(age))-1], 
                                      age[which(is.na(age))+1]))
    age
    # [1] 52.0 27.0 25.0 23.0 39.0 32.0 32.5 33.0 43.0
    

    Or, since you seem to have a single column data.frame:

    mydf <- data.frame(age = c(52, 27, NA, 23, 39, 32, NA, 33, 43))
    
    mydf[is.na(mydf$age), ] <- rowMeans(
      cbind(mydf$age[which(is.na(mydf$age))-1],
            mydf$age[which(is.na(mydf$age))+1]))
    

提交回复
热议问题