简体   繁体   English

如何在R中的xts对象中为日期分配值

[英]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'. 应该为日期“ 2015-05-30”分配值1。 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? 将值分配给空的xts对象的正确方法是什么?

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. 如果需要逐行构建,则以这种方式构建各个向量,并在最后形成xts。

I think you misunderstand the purpose of the [<-.xts function. 我认为您误解了[<-.xts函数的目的。 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. 您要求将日期"2015-05-30"的值替换为1 ,但是您的xts对象没有数据,因此没有任何替换内容。 What are you actually trying to accomplish? 您实际上想完成什么?

If you want to insert, you should call rbind(xts(1, as.Date('2015-05-30')), timeseries) . 如果要插入,则应调用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. 而且,您应该听从Mike Wise的明智建议 :生长这样的物体效率很低。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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