Reputation: 4145
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
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)
set.seed(24)
a <- matrix(ceiling(rnorm(4)), nrow = 2)
l <- mget(rep("a", 3))
Upvotes: 1