Reputation: 28978
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
Upvotes: 3
Views: 1716
Reputation: 121626
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
Upvotes: 1
Reputation: 176748
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
Upvotes: 4