当有NA时插值

时间:2016-02-22 23:34:06

标签: r missing-data

我有纵向数据结构(在 R 中),因为:

dat1 <- data.frame(county = c("a","a","a", "b","b","b", "c","c","c"), year = c(2001, 2002, 2003, 2001, 2002, 2003, 2001, 2002, 2003), count = c(2, NA, 6, 4, NA, 8, 10, NA, 14))

我有一个错过的一年,我想插入 2002 。我做了一个功能:

dat1[dat1$year == 2002,] <- apply(X = data.frame("2001" = dat1[dat1$year == 2001, "count"], "2003" = dat1[dat1$year == 2003, "count"]), MARGIN = 1, FUN = function(x){z <- data.frame(approx(x = x, method = "linear", n = length(2001:2003))$y); return(z[-c(1, nrow(z)),])})
dat1 # the desired result

但只有在我用于插值的两年内没有任何NA时,它才有效:

dat2 <- dat1
dat2[9,3] <- NA

apply(X = data.frame("2001" = dat2[dat2$year == 2001, "count"], "2003" = dat2[dat2$year == 2003, "count"]), MARGIN = 1, FUN = function(x){z <- data.frame(approx(x = x, method = "linear", n = length(2001:2003))$y); return(z[-c(1, nrow(z)),])})

我知道我可以使用complete.cases()使其运行但我无法将其插回到原始数据框中,因为行长度会有所不同。

在上一年或下一年的问题中,是否有人能够解决我的NA问题或更好地解决我的kludge-tastic尝试?

1 个答案:

答案 0 :(得分:2)

如果只有NA,则返回NA,如果只有一个非NA,则使用na.aggregate将单个非NA替换为每个NA,如果一个NA中有多个NA,则使用na.approx县。

library(zoo)

na_approx <- function(x) {
    if (all(is.na(x))) NA 
    else if (sum(!is.na(x)) == 1) na.aggregate(x)
    else na.approx(x, na.rm = FALSE)
}
transform(dat2, count = ave(count, county, FUN = na_approx))

,并提供:

  county year count
1      a 2001     2
2      a 2002     4
3      a 2003     6
4      b 2001     4
5      b 2002     6
6      b 2003     8
7      c 2001    10
8      c 2002    10
9      c 2003    10

这是一种可以略微不同的行为,尽管在这个例子中它给出了相同的结果。

na_approx2 <- function(x) {
     if (sum(!is.na(x)) > 1) na.approx(x, na.rm = FALSE) 
     else na.locf(x, na.rm = FALSE)
}
transform(dat2, count = ave(count, county, FUN = na_approx2))