MolEcologist29
MolEcologist29

Reputation: 151

Modifying elements of matrix in list of lists R

I have a list of lists that contains 40 1x2 matrices. I would like to replace each matrix with a matrix a 2x2 matrix

two of which are the original values, and the other two are 30-original

For example, if I have the following matrix:

matrix(c(2,12),ncol=2,nrow=1)
     [,1] [,2]
[1,]    2   12

I would like a new matrix that looks as follows:

     [,1] [,2]
[1,]    2   12
[2,]   28   18

Whilst I can easily do this individual, or even in just a list, I cannot manage to do this within a list of lists. Here is some example code:

list1<-list()
for (i in 1:10){
  list1[[i]]<-lapply(1:10, matrix, data= runif(2, 12, 30), nrow=1, ncol=2)
}

Upvotes: 0

Views: 42

Answers (1)

gfgm
gfgm

Reputation: 3647

You can do it with two calls to lapply():

l <- list(l1 = matrix(1:2, nrow=1), l2 = matrix(3:4, nrow=1))
l
#> $l1
#>      [,1] [,2]
#> [1,]    1    2
#> 
#> $l2
#>      [,1] [,2]
#> [1,]    3    4

l2 <- list(l, l)

lapply(l2, function(l){lapply(l, function(mat){do.call(rbind, list(mat, 30-mat))})})
#> [[1]]
#> [[1]]$l1
#>      [,1] [,2]
#> [1,]    1    2
#> [2,]   29   28
#> 
#> [[1]]$l2
#>      [,1] [,2]
#> [1,]    3    4
#> [2,]   27   26
#> 
#> 
#> [[2]]
#> [[2]]$l1
#>      [,1] [,2]
#> [1,]    1    2
#> [2,]   29   28
#> 
#> [[2]]$l2
#>      [,1] [,2]
#> [1,]    3    4
#> [2,]   27   26

Created on 2018-03-22 by the reprex package (v0.2.0).

Upvotes: 2

Related Questions