interpolating missing values from a TS
Try this (time series with values of 2, NA , etc. at indicated times (1, 3, etc.) which has NAs removed by linear approx:
library(zoo) z <- zoo(c(2,NA,1,4,5,2), c(1,3,4,6,7,8)) na.approx(z)
1 3 4 6 7 8 2.000000 1.333333 1.000000 4.000000 5.000000 2.000000 zoo has otherl na.* routines too. They work the same way. You just give them the series and the NAs are filled in as in the example above. na.approx - linear approximation to NAs na.contiguous - only keep portion of series with no NAs na.locf - fill NAs from last non-NA na.omit - remove NAs na.spline - spline approximation to NAs na.trim - remove NAs at ends And also in the stinepack package: na.stinterp - use Stineman approxmation to remove NAs See ?na.approx for a few more examples.
On Wed, Oct 7, 2009 at 5:23 AM, Aleks Clark <aleks.clark at gmail.com> wrote:
I've got a large TS with occasional NAs I'd like to roughly
interpolate, I'm currently doing this but it's pretty slow:
? ? ? ?lapply(1:nrow(delta), function(i) {
? ? ? ? ? ? ? ?lapply(1:ncol(delta), function(j) {
? ? ? ? ? ? ? ? ? ? ? ?if (is.na(delta[i,j])) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?if ((i==1)||is.na(delta[i-1,j])) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?delta[i,j] <- delta[i+1,j]
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?} else { delta[i,j] <- delta[i-1,j]}
? ? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ?})
? ? ? ?})
any ideas for a better solution?
--
Aleks Clark
_______________________________________________ R-SIG-Finance at stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-sig-finance -- Subscriber-posting only. -- If you want to post, subscribe first.