Eve Chanatasig
Eve Chanatasig

Reputation: 397

How to replace matrices using lapply?

Let's say that my data has the following structure:

A_matrix<-list(structure(c(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(3L, 3L, 3L)), structure(c(1, 
0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0), .Dim = c(3L, 3L, 3L)))

As<-list(structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1, -2, -3, -4, 
-5, -6, -7, -8, 0, -1, -2, -3, -4, -5, -6, -7, -8), .Dim = c(3L, 
3L, 3L)), structure(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 
5, 6, 7, 8, 9, 0, -1, -2, -3, -4, -5, -6, -7, -8), .Dim = c(3L, 
3L, 3L)))

As you see A_matrix and As are lists which contain arrays. The operation that I would like to do is the following:

for (i in 1:length(A_matrix)) {
      A_matrix[[i]][, , 2] <- A_matrix[[i]][, , 1] %*% As[[i]][, , 1]
    }

However, for is not efficient because my real data is a list with 2800 arrays size (3470, 30, 30) I would like to use a lapply in order to be more efficient. So I though that the following code could function:

    lapply(1:length(As), function(index)
  A_matrix[[index]][, ,2]<-A_matrix[[index]][, , 1] %*% As[[index]][,,1])

But not, I am falling because this code does not replace the second matrix of each array. Can someone help me?

Upvotes: 0

Views: 48

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389135

Return the specific index in each lapply call.

lapply(seq_along(As), function(index) {
  A_matrix[[index]][, ,2] <- A_matrix[[index]][, , 1] %*% As[[index]][,,1]
  A_matrix[[index]]
}) -> B_matrix

Checking the output with for loop -

for (i in 1:length(A_matrix)) {
      A_matrix[[i]][, , 2] <- A_matrix[[i]][, , 1] %*% As[[i]][, , 1]
}

identical(B_matrix, A_matrix)
#[1] TRUE

Upvotes: 0

Related Questions