I have a vector of strings, like
> cc <- c("a", "b", "c")
> cc
[1] "a" "b" "c"
...and I want to build a list (from scratch) with a structure like:
> ll <- list("a" = list("b" = list("c" = "hola")))
> ll
$a
$a$b
$a$b$c
[1] "hola"
What's the easiest way to dynamically access the elements of ll
using cc
?
I know, ultimately, that I want some syntax like:
ll[[cc[1]]][[cc[2]]][[cc[3]]] <- ... # or
ll[["a"]][["b"]][["c"]] <- ...
...which makes me think I want an apply
or lapply
, but it's not simply lapply(cc, ...)
, because that doesn't recursively apply the selection on ll
. It would instead do something like:
ll[c[1]] <- ...
ll[c[2]] <- ...
ll[c[3]] <- ...
So I thought I'd need to use Reduce()
. Because, essentially, what I'm trying to do is apply a function to a variable then apply a function to the result, then apply a function to the result, etc:
temp <- ll[[c[1]]]
temp <- temp[[c[2]]]
temp <- temp[[c[3]]]
...
But I'm not sure this would work either, because we're not saving a reference to ll[[c[1]]]
in temp
, we're saving its value (the second line should throw an error).
I get the feeling that the solution will involve Reduce
, calling the list access function as [[
and maybe a do.call()
, but I'm lost. Any ideas?
Aucun commentaire:
Enregistrer un commentaire