Search code examples
rlistapplymultiplication

multiply vectors stored in a list of a list


I have the following question. I have a list, which holds a list of vectors list like these. Mylist:

[[1]]
[[1]][[1]]
[1]  1  2  3  4  5  6  7  8  9 10

[[1]][[2]]
[1]  6  7  8  9 10 11 12 13 14 15


[[2]]
[[2]][[1]]
[1] 11 12 13 14 15 16 17 18 19 20

[[2]][[2]]
[1] 16 17 18 19 20 21 22 23 24 25

[[3]]
[[3]][[1]]
[1]  3  4  5  6  7  8  9 10 11 12

[[3]][[2]]
[1]  6  7  8  9 10 11 12 13 14 15

....

Each sublist within the list holds only two elements (vectors) and I would like to find a solution to multiply the two vectors stored inside each sublist of the list. In other words Mylist[[1]][[1]]*Mylist[[1]][[2]], Mylist[[2]][[1]]*Mylist[[2]][[2]], Mylist[[3]][[1]]*Mylist[[3]][[2]], and so on... I could easily do a for loop but I know it takes too much time and I would like to know if there is away I can use an apply function or something similar.


Solution

  • You could also use lapply and Reduce:

    lapply(myList, Reduce, f="*")
    [[1]]
     [1]   6  14  24  36  50  66  84 104 126 150
    
    [[2]]
     [1] 176 204 234 266 300 336 374 414 456 500
    

    data, first two list elements in OP's example

    myList <- list(list(1:10, 6:15), list(11:20, 16:25))