Frage

I'm trying create a lookup of sorts, to get a data structure (ideally a zoo) that uses the values in one zoo (myZoo2 below) as column names to look up the values in another (myZoo). A simple example:

require('zoo')
require('tseries')

dates = c('1/1/2000','1/2/2000','1/3/2000')
z1 = zoo(c(1,2,3),dates)
z2 = zoo(c(4,5,6),dates)
z3 = zoo(c(7,8,9),dates)
myZoo = merge(z1,z2,z3)
colnames(myZoo) = c('a', 'b', 'c')

z4 = zoo(c('c', 'b', 'a'), dates)
z5 = zoo(c('b','a','b'), dates)
z6 = zoo(c('c', 'c', 'a'), dates)
myZoo2 = merge(z4,z5,z6)

myZoo
         a b c
1/1/2000 1 4 7
1/2/2000 2 5 8
1/3/2000 3 6 9

myZoo2
         z4 z5 z6
1/1/2000 c  b  c 
1/2/2000 b  a  c 
1/3/2000 a  b  a

I'm looking for the output:

1/1/2000  7  4  7
1/2/2000  5  2  8
1/3/2000  3  6  3

I've been trying multiple different expressions of the form:

myZoo[,colnames=z2]

as well as anonymous functions/ apply etc. Thanks in advance...

War es hilfreich?

Lösung

You need to first get the "coordinates" of the data points that you want.

match(index(myZoo2), index(myZoo)) will match indices of 2 zoo objects, and match(as.vector(myZoo2), names(myZoo)) will get list of column numbers.

Then you subset myZoo with coord to get values that you want. You will still need to "massage" the data back into zoo object manually.

coord <- cbind(match(index(myZoo2), index(myZoo)), match(as.vector(myZoo2), names(myZoo)))

coord
##       [,1] [,2]
##  [1,]    1    3
##  [2,]    2    2
##  [3,]    3    1
##  [4,]    1    2
##  [5,]    2    1
##  [6,]    3    2
##  [7,]    1    3
##  [8,]    2    3
##  [9,]    3    1


zoo(matrix(as.matrix(myZoo)[coord], nrow = nrow(myZoo)), order.by = index(myZoo))
##               
## 1/1/2000 7 4 7
## 1/2/2000 5 2 8
## 1/3/2000 3 6 3
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top