【问题标题】: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 个矩阵元素除以第二个列表中的第 i 个矩阵元素
【发布时间】:2020-09-20 09:53:10
【问题描述】:

我有两个矩阵列表。以下是它们的结构示例:

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)))

我需要将列表中每个矩阵的每个元素与第二个列表中匹配矩阵中的相应元素相除。就好像两个矩阵列表应该是一个数组列表,并且为每个数组元素计算被除数。结果将是:

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

我试过了:

list1/list2 

【问题讨论】:

  • mapply("/",list1,list2)
  • 作为编码风格的建议(请求):不要使用变量旁边的函数 list 命名为 listlist1list2。这在语法上当然是合法的,但是我觉得很难看。
  • 在处理列表时使用什么语法?

标签: r arrays list matrix


【解决方案1】:

使用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

map2 中的purrr

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

【讨论】:

    【解决方案2】:

    我们可以使用seq_alonglapply

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

    【讨论】:

      猜你喜欢
      • 2015-05-06
      • 1970-01-01
      • 2016-07-08
      • 2019-02-18
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多