i have set some environment variables:
envir1 <- new.env()
assign("a", 7, envir=envir1)
assign("b", 8, envir=envir1)
assign("x", 9, envir=envir1)
now i have a list with some of this varibles and some numerics:
lis <- list(1,2, as.name("a"), 5, as.name("x"))
how can i get the numeric value in both ways, when it’s a variable name and when it’s a number
getNumbers2 <- function(li,pos) {
## Part where i dont know
return(li[[pos]]) ## dont works. the name of the variable is returned
}
getNumbers <- function(li,pos, env1) {
environment(getNumbers2) <- env1
getNumbers2(li,pos)
}
getNumbers(lis, 3, envir1)
a ## << wanna have 7 here
Why are you storing the
"a"and"x"as an R symbol?:If you’d just done:
Then this
would have worked:
but that doesn’t work easily inside a function, because of scoping problems.
However, seeing as
with(env1, get(ll[[3]]))works, you probably don’t need the function. Also note thatget()takes an environment as an argument:So we could write the function as
Which does work:
Edit: Just to be clear, if all that is required is to extract an object by name (the position bit threw me as that doesn’t make any sense), then, as @hadley mentions in a comment below, all we really need is to subset the environment using
[[:which, I suppose, if you want to wrap it in a functions would be