lgndrzzz
lgndrzzz

Reputation: 108

Replace multiple values in a list in 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 element in the list with a:

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

What can I do? I tried with:

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

But I can't substitute the new matrix because it's another list and with the [[]] I can only access to one element.

I think I have to use the lapply function but I can't figure out in which way.

Upvotes: 5

Views: 1764

Answers (3)

Aleh
Aleh

Reputation: 826

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 would recommend using modifyList() to update named lists like:

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

Upvotes: 3

MKR
MKR

Reputation: 20095

Another option could be using just far-loop as:

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

Upvotes: 1

jay.sf
jay.sf

Reputation: 73692

Would this work for you?

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

Upvotes: 6

Related Questions