Replace multiple values ​​in a list with R

If I have:

mylist <- lapply(1:10, function(x) matrix(NA, nrow=2, ncol=2))

And I want to replace, for example, the first, second and fifth elements in the list with:

mymatrix=cbind(c(1,1),c(1,1))

What can I do? I tried:

mylist[c(1,2,5)]=mymatrix

But I can not replace the new matrix, because it is a different list, and with the help [[]]I can access only one element.

I think I need to use the function lapply, but I cannot figure out which direction.

+4
source share
3 answers

Will this work for you?

mylist[c(1, 2, 5)] <- lapply(mylist[c(1, 2, 5)], function(x) x <- mymatrix)
+4
source

Similar to @jaSf, but faster and cleaner:

idx <- c(1, 2, 3)
mylist[idx] <- list(mymatrix)

microbenchmark:

Unit: nanoseconds
    expr  min   lq     mean median   uq     max neval cld
    this  687  828 1135.152    959 1127 2787458 1e+05  a 
    jaSf 2982 3575 4482.867   4034 4535 2979424 1e+05   b

Otherwise, it is recommended to use modifyList()to update named lists, for example:

foo <- list(a = 1, b = list(c = "a", d = FALSE))
bar <- modifyList(foo, list(e = 2, b = list(d = TRUE)))
str(foo)
str(bar)
+3
source

Another option can only be used far-loopas:

for(i in c(1,2,5)){
  mylist[[i]] <- mymatrix
}
+1
source

Source: https://habr.com/ru/post/1694103/


All Articles