Replace NA with previous and next rows mean in R

前端 未结 3 1081
余生分开走
余生分开走 2020-12-06 05:41

How could I Replace a NA with mean of its previous and next rows in a fast manner?

  name grade
1    A    56
2    B    NA
3    C    70
4    D    96
         


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 06:24

    Assume you have a data.frame df like this:

    > df
      name grade
    1    A    56
    2    B    NA
    3    C    70
    4    D    96
    5    E    NA
    6    F    95
    

    Then you can use the following:

    > ind <- which(is.na(df$grade))
    > df$grade[ind] <- sapply(ind, function(i) with(df, mean(c(grade[i-1], grade[i+1]))))
    > df
      name grade
    1    A    56
    2    B    63
    3    C    70
    4    D    96
    5    E  95.5
    6    F    95
    

提交回复
热议问题