简体   繁体   English

划分两个矩阵列表,其中一个列表中的第 i 个矩阵元素除以第二个列表中的第 i 个矩阵元素

[英]Divide two lists of matrices where the ith matrix element in one list is divided by the ith matrix element in the second list

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.就好像这两个矩阵列表应该是一个 arrays 列表,并且为每个数组元素计算被除数。 The result would be:结果将是:

list<- list(list1[[1]]/list2[[1]], list1[[2]]/list2[[2]], list1[[3]]/list2[[3]])

I tried:我试过了:

list1/list2 

Use Map :使用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 purrrpurrr中的map2

purrr::map2(list1, list2, `/`)

We can use seq_along with lapply我们可以使用seq_alonglapply

lapply(seq_along(list1), function(i) list1[[i]]/list2[[i]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM