user1266555
user1266555

Reputation: 3

Adding column to xts object based on another xts object in R

I have one main XTS object "Data" with ~1M rows spanning 22 days. I have another XTS object "Set" with 22 rows, with 1 entry per day. I would like to combine this smaller XTS object into the larger one, such that it would have an additional column containing the value in Set for that day.

First I tried:

> Data=cbind(Data,as.numeric(Set[as.Date(index(Data[]))]))
Error in error(x, ...) : 
improper length of one or more arguments to merge.xts

Then I tried:

> Data=cbind(Data,1)
> Data[,6]=as.numeric(Set[as.Date(index(Data[,6]))])
Error in NextMethod(.Generic) : 
  number of items to replace is not a multiple of replacement length

I also tried without the as.numeric but received the same error. I tried turning Data into a data.frame and got the error:

Error in `[<-.data.frame`(`*tmp*`, , 6, value = c(1, 397.16, 397.115,  : 
  replacement has 22 rows, data has 835771

What am I doing wrong and how do I make this happen? I've only been using R the past two weeks.

Thanks!

> str(Data)
An ‘xts’ object from 2012-01-03 05:01:05 to 2012-01-31 14:59:59 containing:
  Data: num [1:835771, 1:5] 397 397 397 397 397 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:5] "SYN" "\"WhitePack.BID_SIZE\"" "\"WhitePack.BID_PRICE\"" "\"WhitePack.ASK_PRICE\"" ...
  Indexed by objects of class: [POSIXct,POSIXt] TZ: 
  xts Attributes:  
 NULL
> str(Set)
An ‘xts’ object from 2012-01-02 to 2012-01-31 containing:
  Data: chr [1:22, 1] "  1.000" "397.160" "397.115" "397.175" "397.200" "397.390" "397.560" "397.580" "397.715" ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "Settle"
  Indexed by objects of class: [POSIXct,POSIXt] TZ: 
  xts Attributes:  
 NULL

Upvotes: 0

Views: 4816

Answers (1)

IRTFM
IRTFM

Reputation: 263352

Do you get success with :

df3 <- merge(Data, Set)

To address my lack of full understanding of the original problem, I think the only additional step would be:

df3[, 6]  <- na.locf( df3[, 6] )

Upvotes: 1

Related Questions