Home > Software design >  How to access objects in an environment printed as hexadecimals without knowing its name
How to access objects in an environment printed as hexadecimals without knowing its name

Time:09-29

I can do:

e <- new.env()
e$a <- 5
e
#> <environment: 0x7f947c27b5e0>

How do I access the list of objects (ls()) stored in environment: 0x7f947c27b5e0 without knowing that it is assigned to object e?

This question stems from an application where an object contains a formula. Objects called for in the formula are stored in a hexadecimal environment which name I get when I print the object. I know the name of the object, but not the name of its environment.

ls()ing the hexadecimal code does not seem to work:

ls(0x7f947c27b5e0)
#> Error in as.environment(pos) : invalid 'pos' argument
#> In addition: Warning message:
#> In ls(140275714864608) : NAs introduced by coercion to integer range

While ls(e) would naturally work.

CodePudding user response:

The envnames package on CRAN looks like it has a useful function (referred to in this question). With that you can do:

library(envnames)
ls(get(environment_name("<environment: 0x7f947c27b5e0>")))
# [1] "a"

CodePudding user response:

The environment function retrieves the, um, environment of a function, formula, or other object.

r$> f <- local({
        a <- 42
        y ~ x
    })

r$> f
y ~ x
<environment: 0x0000024cba3a1958>

r$> environment(f)
<environment: 0x0000024cba3a1958>

r$> ls(environment(f))
[1] "a"

r$> environment(f)$a
[1] 42
  •  Tags:  
  • r
  • Related