Given a list of two lists, I am trying to obtain, without using for loops, a list of all element-wise products of the first list with the second. For example:
> a <- list(c(1,2), c(2,3), c(4,5))
> b <- list(c(1,3), c(3,4), c(6,2))
> c <- list(a, b)
The function should return a list with 9 entries, each of size two. For example,
> answer
[[1]]
[1] 1 6
[[2]]
[1] 3 8
[[3]]
[1] 6 4
[[4]]
[1] 2 9
[[5]]
[1] 6 12
etc...
Any suggestions would be much appreciated!
Have no idea if this is fast or memory intensive just that it works, Joris Meys’s answer is more eloquent:
EDIT: Now that Brian introduced benchmarking (which I love (LINK)) I have to respond. I actually have a faster answer using what I call expand.grid2 that’s a lighter weight version of the original that I stole from HERE. I was going to throw it up before but when I saw how fast Joris’s is I figured why bother, both short and sweet but also fast. But now that Diggs has dug I figured I’d throw up here the
expand.grid2for educational purposes.Here’s the results (same labeling as Bryan’s except TylerEG2 is using the
expand.grid2):And if I take the ordering step out I can squeak out even more but it still isn’t close to Joris’s answer.