Build an xts object with two rows.
library(xts)
junk<-xts(c(1,2),as.Date(c("2010-01-01","2010-05-01")))
junk
> [,1]
> 2010-01-01 1
> 2010-05-01 2
Why doesn't the following change the index for the first row?
time(junk[1])<-as.Date("2010-02-01")
junk
> [,1]
> 2010-01-01 1
> 2010-05-01 2
I realize that the following works, but why doesn't the above work?
time(junk)[1]<-as.Date("2010-02-01")
junk
> [,1]
> 2010-02-01 1
> 2010-05-01 2
Thanks,
Bill
Direct answer to the post is that the magic is inside of attr<-
as Josh says. Subsetting the object first simply creates a new object that gets promptly disposed of once time<- is finished.
In addition you can see the 'internals' of the index via the .index()
function. Essentially an vector of type double or integer that maps to POSIXct time - with some attributes attached. The class you are assigning is automatically coerced back and forth. This makes the internals easier to maintain - and lets you do things with any time class you need outside of it.
In general, Date will be the cleanest way to keep TZ and secs trouble out of the mix, but keep in mind that the cost of this hidden aspect is the function index()
. This will have to recreate the object you expect.
time(junk[1]) <- as.Date("2010-02-01")
The above doesn't change the index of the first row of junk
because subsetting creates a new object--with no reference to junk
--and time<-.xts
replaces the index of the new object.
The dates in time series are not referenced with "[". They are more like rownames in dataframes. They are stored in the "index" leaf of the attributes list. In addition to that, they are not of Date class but rather the DateTime class so you need to may use POSIXct:
> attributes(junk)$index[1] <- as.POSIXct("2010-02-01")
> junk
[,1]
2010-02-01 1
2010-05-01 2
Edit: more accurately the attribute$index is internally in seconds but the time method will accept a variety of assignment classes.
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