Pat
Pat

Reputation: 1339

Looping through xts objects obtaining merged output

I have a couple of xts objects which I need to feed a function with. The function adds a new column to each xts object.

I need help achiving the following two things:

  1. I want to create a merged xts object that contains all values of all the columns that get added to the original xts object
  2. In the new merged xts object I need every column named by a column that has been the name of a column of the original xts object.

Here is an example of what I mean:

require(xts)

A <- xts(rep(1:5), Sys.Date()-5:1)
colnames(A) <- c("AAA")
A$SecondCol <- A[,1] * 10

B <- xts(rep(5:10), Sys.Date()-7:2)
colnames(B) <- c("BBB")
B$SecondCol <- B[,1] * 10

some arbitrary function

myFunction = function(x, n=2){
  x.sma <- runMean(x[,2], n)
  if (!is.null(dim(x.sma))) {
  colnames(x.sma) <- colnames(x[,1])
  }
  return(x.sma)
}

What I am looking for is a smart way such that I obtain an xts object which has AAA and BBB as colum names and the values of the SecondCol of each object:

           AAA BBB
2015-08-17  NA  NA
2015-08-18  NA  55
2015-08-19  NA  65
2015-08-20  15  75
2015-08-21  25  85
2015-08-22  35  95
2015-08-23  45  NA

Upvotes: 0

Views: 998

Answers (1)

Joshua Ulrich
Joshua Ulrich

Reputation: 176738

Your question isn't clear to me, but I can create the xts object with columns "AAA" and "BBB" using myFunction and the objects A and B you provided. Put all your objects in a list. Call your function on each element, and then call merge on the resulting list.

R> do.call(merge, lapply(list(A,B), myFunction))
           AAA BBB
2015-08-18  NA  NA
2015-08-19  NA  55
2015-08-20  NA  65
2015-08-21  15  75
2015-08-22  25  85
2015-08-23  35  95
2015-08-24  45  NA

Upvotes: 2

Related Questions