简体   繁体   English

mapply从两个不同的列表中减去矩阵并返回矩阵列表

[英]mapply to subtract matrices from two different lists and return a list of matrix

I have two lists of matrices, each list has 12 matrices. 我有两个矩阵列表,每个列表都有12个矩阵。 I want to subtract the two matrices from each list. 我想从每个列表中减去两个矩阵。 Here is the reproducible example: 这是可重现的示例:

x1 <- matrix((1:25)*0.1, ncol=5)
x2<-x1+0.3
list1<-list(x1,x2)
list2<-list(x1*2,x2*0.1)
sub<-mapply("-",list1,list2)

This returns the output as 这将输出返回为

    > sub
      [,1] [,2]
 [1,] -0.1 0.36
 [2,] -0.2 0.45
 [3,] -0.3 0.54
 [4,] -0.4 0.63
 [5,] -0.5 0.72
 [6,] -0.6 0.81
 [7,] -0.7 0.90
 [8,] -0.8 0.99
 [9,] -0.9 1.08
[10,] -1.0 1.17
[11,] -1.1 1.26
[12,] -1.2 1.35
[13,] -1.3 1.44
[14,] -1.4 1.53
[15,] -1.5 1.62
[16,] -1.6 1.71
[17,] -1.7 1.80
[18,] -1.8 1.89
[19,] -1.9 1.98
[20,] -2.0 2.07
[21,] -2.1 2.16
[22,] -2.2 2.25
[23,] -2.3 2.34
[24,] -2.4 2.43
[25,] -2.5 2.52

I want the output as a list of 5x5 matrices: eg 我希望将输出作为5x5矩阵的列表:例如

>list1[[1]]-list2[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,] -0.1 -0.6 -1.1 -1.6 -2.1
[2,] -0.2 -0.7 -1.2 -1.7 -2.2
[3,] -0.3 -0.8 -1.3 -1.8 -2.3
[4,] -0.4 -0.9 -1.4 -1.9 -2.4
[5,] -0.5 -1.0 -1.5 -2.0 -2.5

Adding simplify argument to mapply throws the following error: simplify参数添加到mapply会引发以下错误:

Error in .Primitive("-")(dots[[1L]][[1L]], dots[[2L]][[1L]], simplify = dots[[3L]][[1L]]) : 
  operator needs one or two arguments

How can I get the list? 如何获得清单?

As @Sotos comments, use Map which is the wrapper to mapply to output results as a list and not binded matrix. 作为@Sotos评论,请使用Map这是包装mapply输出结果列表,而不是绑定矩阵。 In fact, you can still use mapply but use the SIMPLIFY = FALSE argument. 实际上,您仍然可以使用mapply但可以使用SIMPLIFY = FALSE参数。 NOTE: SIMPLIFY is in ALL CAPS unlike the other apply family argument of same name. 注意: SIMPLIFY包含在ALL CAPS中,与其他同名的apply family参数不同。

Using the default TRUE , mapply is casting each difference into a matrix. 使用默认的TRUE ,mapply将每个差异转换为矩阵。 Below are equivalent calls: 以下是等效调用:

sub1 <- Map(`-`, list1, list2)

sub2 <- mapply(`-`, list1, list2, SIMPLIFY = FALSE)

all.equal(sub1, sub2)
# [1] TRUE

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

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