I have 2 lists whose components are xts objects (co and oc). I want to produce another list object that has the result of oc / co.
> length(co)
[1] 1064
> length(oc)
[1] 1064
> tail(co[[1]])
[,1]
2011-12-22 0.3018297
2011-12-23 0.2987450
2011-12-27 0.2699710
2011-12-28 0.2706428
2011-12-29 0.2098897
2011-12-30 0.2089051
> tail(oc[[1]])
[,1]
2011-12-22 0.6426411
2011-12-23 0.6462834
2011-12-27 0.6466680
2011-12-28 0.6741420
2011-12-29 0.6781371
2011-12-30 0.6650130
> co / oc
Error in co/oc : non-numeric argument to binary operator
If I specify an index of the lists the operation succeeds as follows:
> tail(co[[1]] / oc[[1]])
[,1]
2011-12-22 0.4696707
2011-12-23 0.4622507
2011-12-27 0.4174800
2011-12-28 0.4014627
2011-12-29 0.3095093
2011-12-30 0.3141369
I want to do this without writing a loop to iterate through each component of the two lists (1064 components in total).
Any help would be greatly appreciated. Thank you.
Something like this may work:
mapply("/",co,oc,SIMPLIFY = FALSE)
although there are probably countless ways of doing this that are all mostly equivalent.
Here's a minimal example using some sample data from the xts package:
data(sample_matrix)
sample.xts <- as.xts(sample_matrix, descr='my new xts object')
v1 <- list(a = sample.xts[,1],b = sample.xts[,2])
v2 <- list(a = sample.xts[,3],b = sample.xts[,4])
mapply("/",v1,v2,SIMPLIFY = FALSE)
Update:
We can now use Map
which is basically the mapply(..., simplify = FALSE)
by default.
Map("/",co,oc)