Replacing all NAs with smoothing spline

元气小坏坏 提交于 2019-11-30 21:32:00

I'm using some simplified data for the purposes of answering this query. Take this dataset:

dat <- structure(list(x = c(1.6, 1.6, 4.4, 4.5, 6.1, 6.7, 7.3, 8, 9.5, 
9.5, 10.7), y = c(2.2, 4.5, 1.6, 4.3, NA, NA, 4.8, 7.3, 8.7, 6.3, 12.3)),
.Names = c("x", "y"), row.names = c(NA, -11L), class = "data.frame")

Which looks like the below when plotted using plot(dat,type="o",pch=19):

Now fit a smoothing spline to the data without the NA values

smoo <- with(dat[!is.na(dat$y),],smooth.spline(x,y))

And then predict the y values for x, where y is currently NA

result <- with(dat,predict(smoo,x[is.na(y)]))
points(result,pch=19,col="red")

To fill the values back into the original data you can then do:

dat[is.na(dat$y),] <- result

One thing to check out might be the na.spline function in the zoo package. It appears custom designed for this purpose.

Missing values (NAs) are replaced by linear interpolation via approx or cubic spline interpolation via spline, respectively.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!