Is there something like print method for environment in R?

269 Views Asked by At

I have created a simple environment in R with two simple function,

AnEnv <- new.env()
AnEnv$mod <- function(a, b) a%%b
AnEnv$pwr <- function(a, b) a^b

Whenever I type AnEnv in R-console, it returns something like <environment: 0x7f7f6fe3d4f0>. Is there a why this behaviour can be changed. For example, when I type AnEnv it returns the results from ls(env = AnEnv) or ls.str(env = AnEnv).

2

There are 2 best solutions below

0
On

Perhaps you want something like this:

print.environment = function(x) {
  for (obj in ls(envir=x)) {
    cat(paste0(obj, ": "))
    print(get(obj, envir=x))
  }
}
print (AnEnv)
# mod: function(a, b) a%%b
# pwr: function(a, b) a^b
0
On

R already has ls(e), ls(e, all = TRUE), as.list(e) and str(as.list(e)) which will display the object names (except those that begin with dot), all object names, the entire contents of environment e and a summary of the contents so it is not clear what use this would be; however, we could add a name to an environment and then it will be displayed.

e <- new.env()
attr(e, "name") <- "my env"

e
## <environment: 0x000000001532f8b0>
## attr(,"name")
## [1] "my env"

or use environmentName:

environmentName(e)
## [1] "my env"

In some cases the environment already has a name and/or other attributes.

baseenv()
## <environment: base>

globalenv()
## <environment: R_GlobalEnv>

as.environment("package:graphics")
## <environment: package:graphics>
## attr(,"name")
## [1] "package:graphics"
## attr(,"path")
## [1] "C:/Program Files/R/R-4.1/library/graphics"