Reputation: 795
I have two lists of matrices. Here is an example of their structure:
list1<- list(structure(c(1, 2, 7, 1, 3, 0, 0, 0, 1, 4, 1, 3, 2, 3, 4,
6, 0, 0, 0, 3, 3), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(1,
3, 7, 1, 3, 2, 3, 4, 6, 4, 1, 3, 3, 3), .Dim = c(7L, 2L), .Dimnames = list(
c("lepA", "lepB", "lepC", "lepD", "lepE", "lepF", "lepG"),
NULL)), structure(c(5, 8, 7, 1, 3, 3, 3), .Dim = c(7L, 1L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)))
list2<-list(structure(c(6, 1, 51, 13, 15, 0, 0, 0, 6, 50, 13, 15, 6,
5, 5, 9, 0, 0, 0, 7, 5), .Dim = c(7L, 3L), .Dimnames = list(c("lepA",
"lepB", "lepC", "lepD", "lepE", "lepF", "lepG"), NULL)), structure(c(6,
7, 51, 13, 15, 6, 5, 5, 9, 50, 13, 15, 7, 5), .Dim = c(7L, 2L
), .Dimnames = list(c("lepA", "lepB", "lepC", "lepD", "lepE",
"lepF", "lepG"), NULL)), structure(c(11, 10, 51, 13, 15, 7, 5
), .Dim = c(7L, 1L), .Dimnames = list(c("lepA", "lepB", "lepC",
"lepD", "lepE", "lepF", "lepG"), NULL)))
I need to divide each element of each matrix in a list with the corresponding element in the matching matrix in the second list. It's as though the two lists of matrices should be one list of arrays and the dividend is calculated for each array element. The result would be:
list<- list(list1[[1]]/list2[[1]], list1[[2]]/list2[[2]], list1[[3]]/list2[[3]])
I tried:
list1/list2
Upvotes: 1
Views: 57
Reputation: 887213
We can use seq_along
with lapply
lapply(seq_along(list1), function(i) list1[[i]]/list2[[i]])
Upvotes: 0
Reputation: 389047
Use Map
:
Map(`/`, list1, list2)
#[[1]]
# [,1] [,2] [,3]
#lepA 0.16666667 NaN 0.8000000
#lepB 2.00000000 0.16666667 0.6666667
#lepC 0.13725490 0.08000000 NaN
#lepD 0.07692308 0.07692308 NaN
#lepE 0.20000000 0.20000000 NaN
#lepF NaN 0.33333333 0.4285714
#lepG NaN 0.60000000 0.6000000
#[[2]]
# [,1] [,2]
#lepA 0.16666667 0.80000000
#lepB 0.42857143 0.66666667
#lepC 0.13725490 0.08000000
#lepD 0.07692308 0.07692308
#lepE 0.20000000 0.20000000
#lepF 0.33333333 0.42857143
#lepG 0.60000000 0.60000000
#[[3]]
# [,1]
#lepA 0.45454545
#lepB 0.80000000
#lepC 0.13725490
#lepD 0.07692308
#lepE 0.20000000
#lepF 0.42857143
#lepG 0.60000000
Or map2
in purrr
purrr::map2(list1, list2, `/`)
Upvotes: 1