R separates 2 list objects, each of which contains xts objects of the same size

I have 2 lists whose components are xts (co and oc) objects. I want to create another list object that has the result 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 lists, the operation will be performed 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 each component from two lists (1064 components in total).

Any help would be greatly appreciated. Thanks.

+4
source share
1 answer

Something like this might work:

 mapply("/",co,oc,SIMPLIFY = FALSE) 

although there are probably many ways to do this, which are basically equivalent.

Here is 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: now we can use Map which by default is mapply(..., simplify = FALSE) .

 Map("/",co,oc) 
+7
source

Source: https://habr.com/ru/post/1389007/


All Articles