在dplyr中使用约

Ved*_*dda 2 r approximation dplyr

我正在尝试对使用点id之间的数据帧中的每个进行线性近似. 对于这个似乎是一个合适的选择,但由于一个错误,我无法让它工作:yearxdplyr

错误:大小不匹配(9),期望3(组大小)或1

示例代码:

library(dplyr)
dat <- data.frame(id = c(1,1,1,2,2,2,3,3,3), year = c(1,2,3,1,2,3,1,2,3), x = c(1,NA,2, 3, NA, 4, 5, NA, 6))

# Linear Interpolation
dat %>% 
  group_by(id) %>% 
  mutate(x2 = as.numeric(unlist(approx(x = dat$year, y = dat$x, xout = dat$x)[2])))
Run Code Online (Sandbox Code Playgroud)

样本数据:

  id year  x
1  1    1  1
2  1    2 NA
3  1    3  2
4  2    1  3
5  2    2 NA
6  2    3  4
7  3    1  5
8  3    2 NA
9  3    3  6
Run Code Online (Sandbox Code Playgroud)

G. *_*eck 6

以下是一些方法(从评论中转移):

1)na.approx/ave

library(zoo)

transform(dat, x2 = ave(x, id, FUN = na.approx))
Run Code Online (Sandbox Code Playgroud)

年份为1,2,3,我们不需要指定它,但如果需要,那么:

nr <- nrow(dat)
transform(dat, x2 = ave(1:nr, id, FUN = function(i) with(dat[i, ], na.approx(x, year))))
Run Code Online (Sandbox Code Playgroud)

2)na.approx/dplyr

library(dplyr)
library(zoo)

dat %>% 
    group_by(id) %>% 
        mutate(x2 = na.approx(x, year)) %>% 
    ungroup()
Run Code Online (Sandbox Code Playgroud)

如果不需要年份,则省略第二个参数na.approx.

注意: zoo还有其他NA填充功能,特别是na.splinena.locf.