Jesse Gray
Jesse Gray

Reputation: 37

Modifying an element in a list of matrices

I have generated a list of 100 matrices for a structured population model. I would like to modify element (1,3) of each matrix in the list by multiplying them by a sequence of 100 numbers from 0.01 to 1. The goal is to have row 1, column 3 of the first matrix multiplied by 0.01, the same element in the second matrix by 0.02, and so on.

Thanks

Ls<-6.521
Pg<-.318
Sr<-0.5
Sn<-.432
Sj<-.564
Sa<-.501


AA<-lapply(1:100, 
          function(x) { 
                       matrix(c(0, 0, Sr * rnorm(1,Ls,.3886) * rnorm(1,Pg,.1466), 
                                rnorm(1,Sn,.0954),0,0, 0,rnorm(1,Sj,.0468), 
                                rnorm(1,Sa,.472)), 
                             nrow=3, ncol=3,byrow=TRUE))

Upvotes: 1

Views: 76

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145765

I would just do a for loop, easy and clear:

for(i in seq_along(AA)) {
  AA[[i]][1, 3] = AA[[i]][1, 3] * i / length(AA)
}

Upvotes: 1

Cettt
Cettt

Reputation: 11981

you could use the map2 function from the purrr package. I defined lists with only two matrices and two scalars but should work for you too.

m <- list(m1 = matrix(1, 2, 3),
         m2 = matrix(2, 2, 3))
a <- list(a1 = 0.01, a2 = 0.02)

fun <- function(mymatrix, myx){
  mymatrix[1, 3] <- mymatrix[1, 3]* myx
  return(mymatrix)
} 

purrr::map2(m, a, fun)

$m1
     [,1] [,2] [,3]
[1,]    1    1 0.01
[2,]    1    1 1.00

$m2
     [,1] [,2] [,3]
[1,]    2    2 0.04
[2,]    2    2 2.00

Upvotes: 0

Related Questions