Consider a time series object with several NA
values:
x <- seq(10)
x[seq(2,10,2)] <- NA
x <- ts(x)
Here's the default index:
index(x)
[1] 1 2 3 4 5 6 7 8 9 10
If I remove the NA
values using na.exclude
, I get a new index:
na.exclude(x)
[1] 1 3 5 7 9
attr(,"na.action")
[1] 2 4 6 8 10
attr(,"class")
[1] "exclude"
index(na.exclude(x))
[1] 1 2 3 4 5
If I try na.omit
I just get an error:
na.omit(x)
Error in na.omit.ts(x) : time series contains internal NAs
> index(na.omit(x))
Error in na.omit.ts(x) : time series contains internal NAs
If I try setting the index
to the value I need (and which I expect should be the natural result of removing NA
s), I get another error:
index(x) <- c(1,3,5,7,9)
Error in UseMethod("index<-") : no applicable method for 'index<-'
applied to an object of class "ts"
Is there a direct way to remove the NA
values while preserving the original index for the non-NA
s? I would prefer not to use xts, zoo
, etc., since there are some functions in the package stats
that only accept ts
objects.
Thanks.
You could do this with na.remove
from the tseries
package (which will also keep the ts class):
x <- seq(10)
x[seq(2,10,2)] <- NA
x <- ts(x)
And then:
library(tseries)
na.remove(x)
#Time Series:
#Start = 1
#End = 9
#Frequency = 0.5
#[1] 1 3 5 7 9
#attr(,"na.removed")
#[1] 2 4 6 8 10
index(na.remove(x))
#[1] 1 3 5 7 9
The ts class remains as is:
class(x)
#[1] "ts"
class(na.remove(x))
#[1] "ts"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With