Custom function:
rapply
is only for nested lists; use recursion.
nested_env_list <- function(env) {
out <- as.list(env)
lapply(out, function(x) if (is.environment(x)) nested_env_list(x) else x)
}
Example:
> env <- new.env(); env$a <- new.env(); env$a$b <- 1; env$a$c <- 2; env$d <- 4
> dput(nested_env_list(env))
structure(list(a = structure(list(b = 1, c = 2), .Names = c("b", "c")), d = 4), .Names = c("a", "d"))
Replace built-in as.list
:
You can also replace the behavior of as.list
to ensure this happens throughout whenever you pass an environment to as.list
.
as.list.environment <- function(env) {
out <- base::as.list.environment(env)
lapply(out, function(x) if (is.environment(x)) as.list(x) else x)
}
Then R will figure it out automatically for all future environments. If you want the old behavior in a few select places, use base::as.list.environment
explicitly.
Example:
> env <- new.env(); env$a <- new.env(); env$a$b <- 1; env$a$c <- 2; env$d <- 4
> dput(as.list(env))
structure(list(a = structure(list(b = 1, c = 2), .Names = c("b", "c")), d = 4), .Names = c("a", "d"))
Finally, you should ask yourself why you get infinite recursion if you replace out <- base::as.list.environment(env)
above with out <- base::as.list(env)
.