user2026971
user2026971

Reputation: 45

Updating an XTS object

I've been struggling to do something is probably horribly simple on R. What I am trying to do is to update a XTS object column using another XTS object.

Let's say I have the following XTS object, named Object1:

A B
2000-01-03 , 14, NA
2000-01-04 , NA, NA
2000-01-05 , 16, 100
2000-01-06 , NA, 200

And the following XTS object, named Object2:

A
2000-01-05 , 160
2000-01-06 , 20

I am looking for a way to update Object1 with values from Object2, having the following result:

A B
2000-01-03 , 14, NA
2000-01-04 , NA, NA
2000-01-05 , 160, 100
2000-01-06 , 20, 200

If I do merge(Object1,Object2), I will have:

A B A.1
2000-01-03 , 14, NA, NA
2000-01-04 , NA, NA, NA
2000-01-05 , 16, 100, 160
2000-01-06 , NA, 200, 20

Which is absolutely not what I'm looking for, since I am trying to update Object1$A based on Object2$A.

What am I missing here?

Here is the output of dput(Object1) and dput(Object2) to make this reproducible:

> dput(Object1)
structure(c(14, NA, 16, NA, NA, NA, 100, 200), .Dim = c(4L, 2L
), index = structure(c(946857600, 946944000, 947030400, 947116800
), tzone = "UTC", tclass = "Date"), .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", .Dimnames = list(
    NULL, c("A", "B")), class = c("xts", "zoo"))

> dput(Object2)
structure(c(160, 20), .Dim = c(2L, 1L), index = structure(c(947030400, 
947116800), tzone = "UTC", tclass = "Date"), .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", .Dimnames = list(
    NULL, "A"), class = c("xts", "zoo"))

Upvotes: 4

Views: 477

Answers (1)

GSee
GSee

Reputation: 49820

You can subset Object1 using the index of Object2

> Object1[index(Object2), "A"] <- Object2$A
> Object1
             A   B
2000-01-03  14  NA
2000-01-04  NA  NA
2000-01-05 160 100
2000-01-06  20 200

Upvotes: 4

Related Questions