Search code examples
rlistmatrixsubtraction

Subtraction of list of matrix within a list in R


I have a list of which consists of list of matrices as follows:

$A
$A[[1]]
$A[[1]][[1]]
     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10


$A[[2]]
$A[[2]][[1]]
     [,1] [,2]
[1,]    2    7
[2,]    3    8
[3,]    4    9
[4,]    5   10
[5,]    6   11



$B
$B[[1]]
$B[[1]][[1]]
     [,1] [,2]
[1,]   11   16
[2,]   12   17
[3,]   13   18
[4,]   14   19
[5,]   15   20


$B[[2]]
$B[[2]][[1]]
     [,1] [,2]
[1,]   12   17
[2,]   13   18
[3,]   14   19
[4,]   15   20
[5,]   16   21



$C
$C[[1]]
$C[[1]][[1]]
     [,1] [,2]
[1,]    0    0
[2,]    0    0
[3,]    0    0
[4,]    0    0
[5,]    0    0


$C[[2]]
$C[[2]][[1]]
     [,1] [,2]
[1,]    0    0
[2,]    0    0
[3,]    0    0
[4,]    0    0
[5,]    0    0

The above list of matrices was created using the codes below:

A_mat1 <- matrix(as.numeric(c(1:10)), nrow = 5, ncol = 2)
B_mat1 <- matrix(as.numeric(c(11:20)), nrow = 5, ncol = 2)
C_mat1 <- matrix(as.numeric(0), nrow = 5, ncol = 2)
A_mat2 <- matrix(as.numeric(c(2:11)), nrow = 5, ncol = 2)
B_mat2 <- matrix(as.numeric(c(12:21)), nrow = 5, ncol = 2)
C_mat2 <- matrix(as.numeric(0), nrow = 5, ncol = 2)

my_matrix_name <- as.vector(c("A_mat1", "B_mat1", "C_mat1", "A_mat2", "B_mat2", "C_mat2"))
my_list = list(A_mat1, B_mat1, C_mat1, A_mat2, B_mat2, C_mat2)
names(my_list) <- my_matrix_name

my_A <- as.vector(my_matrix_name[substring(my_matrix_name,1,1) == "A"])
my_B <- as.vector(my_matrix_name[substring(my_matrix_name,1,1) == "B"])
my_C <- as.vector(my_matrix_name[substring(my_matrix_name,1,1) == "C"])

A = list()
for(i in seq_len(length(my_A))){
  A[[i]] <- list(my_list[[paste0(my_A[[i]])]])
}

B = list()
for(i in seq_len(length(my_B))){
  B[[i]] <- list(my_list[[paste0(my_B[[i]])]])
}

C = list()
for(i in seq_len(length(my_C))){
  C[[i]] <- list(my_list[[paste0(my_C[[i]])]])
}

my_group = list(A,B,C)
names(my_group) <- c("A", "B", "C")
my_group

Where group C matrices have values of 0. Now I want to create a formula to overwrite group C equals to group A minus group B i.e. C = A - B

I have tried using

my_group[[3]] = my_group[[1]] - my_group[[2]]

and

my_group[[3]] = Map("-", my_group[[1]] , my_group[[2]])

but it gives error message: non-numeric argument to binary operator. Can anyone help me please? Thanks!


Solution

  • Because you have nested lists, your Map function is actually trying to subtract a list from another list. You need your mapping function to extract the first element of each list and subtract those

    Map(function(A, B) A[[1]] - B[[1]], my_group$A , my_group$B)
    #> [[1]]
    #>      [,1] [,2]
    #> [1,]  -10  -10
    #> [2,]  -10  -10
    #> [3,]  -10  -10
    #> [4,]  -10  -10
    #> [5,]  -10  -10
    #> 
    #> [[2]]
    #>      [,1] [,2]
    #> [1,]  -10  -10
    #> [2,]  -10  -10
    #> [3,]  -10  -10
    #> [4,]  -10  -10
    #> [5,]  -10  -10