[英]How to update a row in a multi-column XTS object?
Given a single-column xts object, I can update a row like this: 给定一个单列xts对象,我可以像这样更新一行:
library(xts)
a=xts(1:5,Sys.Date()+1:5)
b=xts(77:77,Sys.Date()+2)
a[index(b)]=b
But once I have 2+ rows it fails with " number of items to replace is not a multiple of replacement length ": 但是一旦我有2+行,它就会失败并显示“ 要替换的项目数不是替换长度的倍数 ”:
a=xts(1:5,Sys.Date()+1:5);colnames(a)='x';a$y=11:15
b=xts(77:77,Sys.Date()+2);colnames(b)='x';b$y=78:78
a[index(b)]=b
How should I update a single row in an xts object? 如何更新xts对象中的一行?
For the moment I have this hack: 目前我有这个hack:
a$x[index(b)]=b$x
a$y[index(b)]=b$y
Is there a better way? 有没有更好的办法?
Expected Result: 预期结果:
> a
x y
2012-12-24 1 11
2012-12-25 77 78
2012-12-26 3 13
2012-12-27 4 14
2012-12-28 5 15
The easiest way is to use a comma in your subsetting command: 最简单的方法是在子命令中使用逗号:
a=xts(1:5,Sys.Date()+1:5);colnames(a)='x';a$y=11:15
b=xts(77:77,Sys.Date()+2);colnames(b)='x';b$y=78:78
a[index(b),]=b
one solution is to use coredata
, to manipulate matrix 一种解决方案是使用
coredata
来操纵矩阵
coredata(a)[index(a)==index(b)] <- coredata(b)
> a
x y
2012-12-24 1 11
2012-12-25 77 78
2012-12-26 3 13
2012-12-27 4 14
2012-12-28 5 15
I would prefer to use a[index(b),]=b as mentioned in the other answer , but for some reasons when I use it I don't have the same result. 我宁愿使用另一个答案中提到的a [index(b),] = b,但是由于某些原因,当我使用它时,我没有相同的结果。 (It changes the first date not the second one)
(它将更改第一个日期,而不是第二个)
a=xts(1:5,Sys.Date()+1:5);colnames(a)='x';a$y=11:15
> b=xts(77:77,Sys.Date()+2);colnames(b)='x';b$y=78:78
> a[index(b),]=b
> a
x y
2012-12-23 77 78
2012-12-24 2 12
2012-12-25 3 13
2012-12-26 4 14
2012-12-27 5 15
with 同
> b
x y
2012-12-24 77 78
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.