I would like to find an efficient operation to do the following look up in a list:
L = list(10:15,11:20)
a = c(3,7)
b = numeric()
for(i in 1:length(a)) b[i] = L[[i]][a[i]]
I think for
loops are inefficient and I imagine this can be done faster using, for example, sapply
. My main goal is to do this efficiently when L
is long.
CodePudding user response:
Another apply
method would be sapply()
.
sapply(1:length(a), function(x) L[[x]][a[x]])
[1] 12 17
CodePudding user response:
You could use Map
or mapply
. Since mapply
can automatically simplify to a vector, we can could use that here to get b
in one go:
b <- mapply(function(list_members, indices) list_members[indices],
list_members = L, indices = a, SIMPLIFY = TRUE)
b
#> [1] 12 17
CodePudding user response:
We could use
library(dplyr)
stack(setNames(L, a)) %>%
group_by(ind) %>%
summarise(out = values[[as.numeric(as.character(first(ind)))]]) %>%
pull(out)
[1] 12 17
Or in base R
using vapply
which would be faster
vapply(seq_along(L), \(i) L[[i]][a[i]], numeric(1))
[1] 12 17
or use imap
as a compact option
library(purrr)
imap_dbl(setNames(L, a), ~ .x[as.numeric(.y)])
3 7
12 17