用平滑样条替换所有NA [英] Replacing all NAs with smoothing spline
本文介绍了用平滑样条替换所有NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是样本数据(约8000行数据).如何用平滑样条拟合到其余数据的值替换所有NA?
Below is the sample data (out of approximately 8000 rows of data). How can I replace all NAs with values from a smoothing spline fit to the rest of the data?
Date Max Min Rain RHM RHE
4/24/1981 35.9 24.7 0.0 71 37
4/25/1981 36.8 22.8 0.0 62 40
4/26/1981 36.0 22.6 0.0 47 37
4/27/1981 35.1 24.2 0.0 51 39
4/28/1981 35.4 23.8 0.0 61 47
4/29/1981 35.4 25.1 0.0 67 43
4/30/1981 37.4 24.8 0.0 72 34
5/1/1981 NA NA NA NA NA
5/2/1981 39.0 25.3 NA NA 55
5/3/1981 35.9 23.0 0.0 68 66
5/4/1981 28.4 22.4 0.7 70 30
5/5/1981 35.5 24.6 0.0 47 31
5/6/1981 37.4 25.5 0.0 51 31
推荐答案
我正在使用一些简化的数据来回答此查询.取得此数据集:
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")
使用plot(dat,type="o",pch=19)
绘制时的外观如下所示:
Which looks like the below when plotted using plot(dat,type="o",pch=19)
:
现在将平滑样条拟合到没有NA
值的数据
Now fit a smoothing spline to the data without the NA
values
smoo <- with(dat[!is.na(dat$y),],smooth.spline(x,y))
然后预测x
的y
值,其中y
当前为NA
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
这篇关于用平滑样条替换所有NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文