用一个平均值替换多个 NA
Replacing multiple NA's with one mean
我有以下类型的向量:
x <- c(2,5,1,5,NA,NA,NA,9,23,1,NA,NA,NA,5,2)
有没有办法用 NA 前后的值的平均值替换我的 NA?就像对它们进行插值一样,但只有一个值!
*更新:这种情况下的预期输出为 c(2,5,1,5,7,7,7,9,23,1,3,3,3,5,2)
非常感谢。
我们可以使用 na.approx
从 zoo
library(zoo)
na.approx(x, method = "constant", f = .5)
# [1] 2 5 1 5 7 7 7 9 23 1 3 3 3 5 2
关于f
的争论,来自?approxfun
for method = "constant" a number between 0 and 1 inclusive, indicating a compromise between left- and right-continuous step functions. If y0 and y1 are the values to the left and right of the point then the value is y0 if f == 0, y1 if f == 1, and y0*(1-f)+y1*f for intermediate values. In this way the result is right-continuous for f == 0 and left-continuous for f == 1, even for non-finite y values
我有以下类型的向量:
x <- c(2,5,1,5,NA,NA,NA,9,23,1,NA,NA,NA,5,2)
有没有办法用 NA 前后的值的平均值替换我的 NA?就像对它们进行插值一样,但只有一个值!
*更新:这种情况下的预期输出为 c(2,5,1,5,7,7,7,9,23,1,3,3,3,5,2)
非常感谢。
我们可以使用 na.approx
从 zoo
library(zoo)
na.approx(x, method = "constant", f = .5)
# [1] 2 5 1 5 7 7 7 9 23 1 3 3 3 5 2
关于f
的争论,来自?approxfun
for method = "constant" a number between 0 and 1 inclusive, indicating a compromise between left- and right-continuous step functions. If y0 and y1 are the values to the left and right of the point then the value is y0 if f == 0, y1 if f == 1, and y0*(1-f)+y1*f for intermediate values. In this way the result is right-continuous for f == 0 and left-continuous for f == 1, even for non-finite y values