I have a list of lists p
p <- list(1:5,4:8,7:11)
and another list of lists
q <- list(2:3,1:2,4:5)
I want to set for each list in p and a corresponding list in q,
p[q] <- Inf;
For instance, (1:5) [2:3] <- Inf, (4:8) [1:2] <- inf, and (7:11) [4:5] <- Inf;
How can I achieve that? The end result of the function would be updated list of lists. Thanks.
mapply / [<-
> mapply("[<-", p, q, Inf, SIMPLIFY = FALSE)
[[1]]
[1] 1 Inf Inf 4 5
[[2]]
[1] Inf Inf 6 7 8
[[3]]
[1] 7 8 9 Inf Inf
mapply / replace
mapply(replace, p, q, Inf, SIMPLIFY = FALSE)
lapply / replace
lapply(seq_along(p), function(i) replace(p[[i]], q[[i]], Inf))
for
for(i in seq_along(p)) p[[i]][ q[[i]] ] <- Inf
replace / melt
If each component of p has the same length (as the example in the question does) we can turn p into a data.frame which opens up additional possibilities. This returns a data frame:
library(reshape2)
replace(as.data.frame(p), as.matrix(melt(q)), Inf)
vapply / replace
This also assumes that each component of p has the same length returning a matrix:
vapply(seq_along(p), function(i) replace(p[[i]], q[[i]], Inf), 0 * p[[1]])
REVISED Minor improvements plus alternatives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With