Pergunta

If one of my tables has multiple values for the time stamp, and the other just one, can I repeat the value of the single item in the multiple values?

For instance:

XTS_A:

2011/01/01 10:00:00,Bar
2011/01/01 10:00:01,Baz

XTS_B:

2011/01/01 10:00:00,A
2011/01/01 10:00:00,B
2011/01/01 10:00:00,C
2011/01/01 10:00:01,B

Merge_Result:

2011/01/01 10:00:00,A,Bar
2011/01/01 10:00:00,B,Bar
2011/01/01 10:00:00,C,Bar
2011/01/01 10:00:01,B,Baz

Reproducible example:

library(zoo)
library(xts)
XTS_A <- structure(c("Bar", "Baz"), .Dim = c(2L, 1L), index = structure(c(1293894000, 1293894001), tzone = "", tclass = c("POSIXt", "POSIXct")), class = c("xts",  "zoo"), .indexCLASS = c("POSIXt", "POSIXct"), .indexTZ = "")
XTS_B <- structure(c("A", "B", "C", "B"), .Dim = c(4L, 1L), index = structure(c(1293894000,  1293894000, 1293894000, 1293894001), tzone = "", tclass = c("POSIXt",  "POSIXct")), class = c("xts", "zoo"), .indexCLASS = c("POSIXt",  "POSIXct"), .indexTZ = "")
Foi útil?

Solução

What about just filling down afterwards? Somewhat ugly example (uses a loop, but hard to avoid with sequential dependencies like this):

mrg <- merge(XTS_A,XTS_B)
for(r in seq(nrow(mrg)) ) {
  if(is.na(mrg[r,1])) {
    mrg[r,1] <- mrg[r-1,1] 
  }
}

> mrg
                    XTS_A XTS_B
2011-01-01 16:00:00 "Bar" "A"  
2011-01-01 16:00:00 "Bar" "B"  
2011-01-01 16:00:00 "Bar" "C"  
2011-01-01 16:00:01 "Baz" "B"

Joran's suggestion saves typing using the zoo package's fill-down function:

mrg[,1] <- na.locf(as.vector(mrg$XTS_A))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top