2

Say I have three lists:

 l_zero
[[1]]
     [,1] [,2]
[1,]    0    0
[2,]    0    0

[[2]]
     [,1] [,2]
[1,]    0    0
[2,]    0    0

l_ind <- list(matrix(c(1,1), ncol = 2), matrix(c(1,1,1,2), ncol = 2))
l_ind
[[1]]
     [,1] [,2]
[1,]    1    1

[[2]]
     [,1] [,2]
[1,]    1    1
[2,]    1    2

l_val <- list(5, c(4, 7))
l_val
[[1]]
[1] 5

[[2]]
[1] 4 7

I would like to run Map over the three lists with the goal of replacing in l_zero the zeros with the coordinates in l_ind with the values from l_val. My attempt gives me the following:

Map(function(l_zero, l_ind, l_val) l_zero[l_ind] <- l_val, l_zero = l_zero, l_ind = l_ind, l_val = l_val)
[[1]]
[1] 5

[[2]]
[1] 4 7

As you can see, the original dimensions of the matrices are reduced, but I would like to keep the dimensions of the matrices and just replace the values with the coordinates in l_ind. I tried l_zero[l_ind, drop = FALSE], but that didn't help either.

Can someone help me with this?

DatamineR
  • 10,428
  • 3
  • 25
  • 45

2 Answers2

4

Here's a bit simpler method, The [<- replacement function can be used in Map()'s function argument. It takes three arguments, in order.

Map("[<-", l_zero, l_ind, l_val)
# [[1]]
#      [,1] [,2]
# [1,]    5    0
# [2,]    0    0
# 
# [[2]]
#      [,1] [,2]
# [1,]    4    7
# [2,]    0    0
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
1

You need to return the modified value from your mapped function (see return(l_zero) below).

l_zero <- replicate(2,matrix(0,2,2),simplify=FALSE)
l_ind <- list(matrix(c(1,1), ncol = 2), matrix(c(1,1,1,2), ncol = 2))
l_val <- list(5, c(4, 7))

ff <- function(l_zero, l_ind, l_val) {
    l_zero[l_ind] <- l_val
    return(l_zero)
}
Map(ff, l_zero = l_zero, l_ind = l_ind, l_val = l_val)

Results:

## [[1]]
##      [,1] [,2]
## [1,]    5    0
## [2,]    0    0
## 
## [[2]]
##      [,1] [,2]
## [1,]    4    7
## [2,]    0    0
Ben Bolker
  • 211,554
  • 25
  • 370
  • 453