1

I have read Multiplying Combinations of a list of lists in R. But i can't still apply it on my case.

I have two different lists in R:

x <- list(matrix(1:4,nrow=2), matrix(5:8, nrow=2))
y <- list(matrix(c(1,0,0,1), nrow=2), matrix(c(0,1,0,1), nrow=2) )

I want to multiply the 1st element of x with the 1st element of y; the 2nd element of x with the 2nd element of y. That is,

x[[1]] * y[[1]]
x[[2]] * y[[2]]

But I don't want to write one line code for each element since I have 100 elements in each list.

Community
  • 1
  • 1
ABC
  • 341
  • 3
  • 10
  • See either `?mapply` or `?Map`. – Frank Mar 03 '17 at 05:16
  • 2
    I'm not given the ability to answer, but another possibility is to use the `purrr` package with the following line: `map2(x, y, function(x, y) x*y)` – Phil Mar 03 '17 at 06:37

1 Answers1

2

You can use map as shown below:

Map('*',x,y)

Output of the above code is shown below:

> Map('*',x,y)
  [[1]]
      [,1] [,2]
[1,]    1    0
[2,]    0    4

 [[2]]
      [,1] [,2]
[1,]    0    0
[2,]    6    8

OR

You can use unlist to unlist list and multiple list together:

Listxy <- list(unlist(x)*unlist(y))
Listxy
[[1]]
[1] 1 0 0 4 0 6 0 8
Saurabh Chauhan
  • 3,161
  • 2
  • 19
  • 46