在dplyr中使用近似值
我试图使用点在dplyr中使用近似值,r,dplyr,approximation,R,Dplyr,Approximation,我试图使用点x对年之间的数据帧中的每个id进行线性近似dplyr似乎是一个合适的选项,但由于出现错误,我无法使其工作: 错误:大小不兼容(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 %>%
x
对年之间的数据帧中的每个id
进行线性近似dplyr
似乎是一个合适的选项,但由于出现错误,我无法使其工作:
错误:大小不兼容(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])))
您可以在base R中执行此操作:
dat <- dat[order(dat$id, dat$year),]
dat$x2 <- unlist(by(dat, dat$id, function(df) approx(df$year, df$x, xout = df$year)[2]))
dat
id year x x2
1 1 1 1 1.0
2 1 2 NA 1.5
3 1 3 2 2.0
4 2 1 3 3.0
5 2 2 NA 3.5
6 2 3 4 4.0
7 3 1 5 5.0
8 3 2 NA 5.5
9 3 3 6 6.0
dat以下是两种方法(从注释转移):
1)na.近似值/平均值
library(zoo)
transform(dat, x2 = ave(x, id, FUN = na.approx))
第1年、第2年、第3年,我们不需要具体说明,但如果需要:
nr <- nrow(dat)
transform(dat, x2 = ave(1:nr, id, FUN = function(i) with(dat[i, ], na.approx(x, year))))
如果不需要年份,则省略na.approx
的第二个参数
注意:zoo还有其他NA填充功能,特别是NA.spline
和NA.locf
谢谢,但是您有dplyr
解决方案吗?@G.Grothendieck谢谢。这会奏效的。添加答案,我将接受可能重复的相关帖子:
nr <- nrow(dat)
transform(dat, x2 = ave(1:nr, id, FUN = function(i) with(dat[i, ], na.approx(x, year))))
library(dplyr)
library(zoo)
dat %>%
group_by(id) %>%
mutate(x2 = na.approx(x, year)) %>%
ungroup()