用R中的上一行和下一行平均值替换NA [英] Replace NA with previous and next rows mean in R

查看:20
本文介绍了用R中的上一行和下一行平均值替换NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何快速用前一行和下一行的平均值替换 NA?

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

这样 B 的成绩就是 63.

such that B's grade would be 63.

推荐答案

或者您可以尝试 na.approx 包中的 zoo:替换缺失值 (NAs)通过线性插值"

Or you may try na.approx from package zoo: "Missing values (NAs) are replaced by linear interpolation"

library(zoo)
x <- c(56, NA, 70, 96)
na.approx(x)
# [1] 56 63 70 96

如果您有多个连续的NA,这也适用:

This also works if you have more than one consecutive NA:

vals <- c(1, NA, NA, 7, NA, 10)
na.approx(vals) 
# [1]  1.0  3.0  5.0  7.0  8.5 10.0

na.approx 是基于 base 函数 approx,可以替代使用:

na.approx is based on the base function approx, which may be used instead:

vals <- c(1, NA, NA, 7, NA, 10)
xout <- seq_along(vals)
x <- xout[!is.na(vals)]
y <- vals[!is.na(vals)]

approx(x = x, y = y, xout = xout)$y
# [1]  1.0  3.0  5.0  7.0  8.5 10.0

这篇关于用R中的上一行和下一行平均值替换NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆