简体   繁体   中英

How to assign value to a date in an xts object in R

I assumed the following code

date = as.Date('2015-05-30')
timeseries = xts()
timeseries[date] = 1

should assign the value of 1 to a date '2015-05-30'. However, it gives me an error

Error in xts(rep(NA, length(index(x))), index(x)) : 
  order.by requires an appropriate time-based object

What is the proper way to assign the value to an empty xts object?

Thanks, Vladimir

Try something like this:

d1 <- rep(1,21)
d2 <- seq(as.Date("2001-01-01",tz="GMT"),as.Date("2021-01-01",tz="GMT"),length.out=21)
xtsdat <- as.xts(d1,d2)

If you need to build it up row by row, then build the individual vectors that way and form the xts at the end.

I think you misunderstand the purpose of the [<-.xts function. You're asking to replace the value at date "2015-05-30" with 1 , but your xts object has no data, so there's nothing to replace. What are you actually trying to accomplish?

If you want to insert, you should call rbind(xts(1, as.Date('2015-05-30')), timeseries) .


And you should heed Mike Wise's wise advice : it is very inefficient to grow objects like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM