用R插值多个NA值

时间:2014-09-02 14:09:34

标签: r na interpolation

我想在名为tester的矩阵中插入多个NA值。

这是测试仪的一部分,只有1列NA值,在整个744x6矩阵中,其他列也有多个:

ZONEID   TIMESTAMP         U10            V10            U100          V100
1        20121022 12:00    -1.324032e+00  -2.017107e+00 -3.278166e+00  -5.880225574
1        20121022 13:00    -1.295168e+00            NA  -3.130429e+00  -6.414975148
1        20121022 14:00    -1.285004e+00            NA  -3.068829e+00  -7.101699541
1        20121022 15:00    -9.605904e-01            NA  -2.332645e+00  -7.478168285
1        20121022 16:00    -6.268261e-01 -3.057278e+00  -1.440209e+00  -8.026791079

我已安装zoo包并使用代码library(zoo)。我试图使用na.approx函数,但它以线性方式返回:

na.approx(tester)
# Error ----> need at least two non-NA values to interpolate

na.approx(tester, rule = 2)
# Error ----> need at least two non-NA values to interpolate

na.approx(tester, x = index(tester), na.rm = TRUE, maxgap = Inf)

之后我尝试了:

Lines <- "tester"
library(zoo) 
z <- read.zoo(textConnection(Lines), index = 2)[,2] 
na.approx(z)

我再次得到了相同的多个NA值错误。我也尝试过:

z <- zoo(tester)
index(Cz) <- Cz[,1]
Cz_approx <- na.approx(Cz)

同样的错误。

我必须做一些非常愚蠢的事情,但我真的很感谢你的帮助。

1 个答案:

答案 0 :(得分:8)

您只能对具有至少两个非na.approx值的列应用NA。在这里,我在布尔矩阵上使用colSums来查找相关列。

# create a small matrix
m <- matrix(data = c(NA, 1, 1, 1, 1,
                     NA, NA, 2, NA, NA,
                     NA, NA, NA, NA, 2,
                     NA, NA, NA, 2, 3),
            ncol = 5, byrow = TRUE)

m
#      [,1] [,2] [,3] [,4] [,5]
# [1,]   NA    1    1    1    1
# [2,]   NA   NA    2   NA   NA
# [3,]   NA   NA   NA   NA    2
# [4,]   NA   NA   NA    2    3

library(zoo)

# na.approx on the entire matrix does not work
na.approx(m)
# Error in approx(x[!na], y[!na], xout, ...) : 
#   need at least two non-NA values to interpolate

# find columns with at least two non-NA values
idx <- colSums(!is.na(m)) > 1
idx
# [1] FALSE FALSE  TRUE  TRUE  TRUE

# interpolate 'TRUE columns' only
m[ , idx] <- na.approx(m[ , idx])
m
#      [,1] [,2] [,3]     [,4] [,5]
# [1,]   NA    1    1 1.000000  1.0
# [2,]   NA   NA    2 1.333333  1.5
# [3,]   NA   NA   NA 1.666667  2.0
# [4,]   NA   NA   NA 2.000000  3.0