简体   繁体   中英

How to update a row in a multi-column XTS object?

Given a single-column xts object, I can update a row like this:

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 ":

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?

For the moment I have this 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(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. (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

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