0

I want to merge MANY xts objects in a loop. In order to do so, i have to write the following code 138 times. temp=merge(temp,temp1) temp=merge(temp,temp2) temp=merge(temp,temp3) temp=merge(temp,temp4) is there a way to automate that procedure?

1 Answers1

1

Create a list which contains the objects and then use do.call/merge. Below we could hae omitted the component names of the list if the xts objects themselves had column names. Although in this example the dates are the same it will still work if they are not.

library(xts)

# test data
x1 <- x2 <- x3 <- xts(1:3, as.Date("2000-01-01") + 0:2)

L <- list(x1 = x1, x2 = x2, x3 = x3)
do.call("merge", L)

giving:

           x1 x2 x3
2000-01-01  1  1  1
2000-01-02  2  2  2
2000-01-03  3  3  3

If the xts objects have a pattern to their names, e.g. they are the only objects whose names start with x then this alternative would also work to create L:

L <- mget(ls(pattern = "^x"))

or if they are the only xts objects then this would work to create the list.

L <- Filter(is.xts, mget(ls()))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341