Manuel R
Manuel R

Reputation: 4145

Add different values to each matrix in a list

Can't get my head wraped around this problem. I know how to do it the dirty -for-loop-way, but I am sure there is some elegant base-R or purrr approach.

I have a list of n matrices that are the same:


a <- matrix(ceiling(rnorm(4)), nrow = 2)
l <- list(mget(rep("a", 3)))        
l
#> [[1]]
#> [[1]]$a
#>      [,1] [,2]
#> [1,]    2    2
#> [2,]    0    0
#> 
#> [[1]]$a
#>      [,1] [,2]
#> [1,]    2    2
#> [2,]    0    0
#> 
#> [[1]]$a
#>      [,1] [,2]
#> [1,]    2    2
#> [2,]    0    0

x <- 1:3

Now I want to replace in each matrix i, say, the [1,2] element by the i'th value in x.

How do I do that?

Upvotes: 1

Views: 30

Answers (1)

akrun
akrun

Reputation: 887213

We can use Map

Map(function(x,y) replace(x, 3, y), l, x)

Or

Map(function(x,y) {x[1,2] <- y; x}, l, x)

data

set.seed(24)
a <- matrix(ceiling(rnorm(4)), nrow = 2)
l <- mget(rep("a", 3)) 

Upvotes: 1

Related Questions