The global environment seems to have the name R_GlobalEnv
environment()
# <environment: R_GlobalEnv>
I'd like to attach a name to a new environment e
so that if I name it myEnv, it reads
e
# <environment: myEnv>
But it doesn't seem like this is possible. There are no arguments in new.env
that allow this, and attr<-
doesn't seem to work.
e <- new.env()
attr(e, "names") <- "myEnv"
# Error in attr(e, "names") <- "myEnv" : names() applied to a non-vector
Is it possible to name the environment, maintain the byte code, and have it print as shown above?
Creating a new environment named new_name. Copy files manually from the old environment old_name to the location of new environment. Fix the references to old name within the files. Delete the old environment and the new environment is the renamed version.
From ?environment
:
System environments, such as the base, global and empty environments, have names as do the package and namespace environments and those generated by ‘attach()’. Other environments can be named by giving a ‘"name"’ attribute
Therefore:
attr(e, "name") <- "yip"
e
#<environment: 0x00000000080974f8>
#attr(,"name")
#[1] "yip"
environmentName(e)
#[1] "yip"
You can give it a class and write an S3 print
method
> e <- new.env()
> class(e) <- "myClass"
> print.myClass <- function(x, ...) cat("<environment: myEnv>\n")
> e
<environment: myEnv>
Combining @thelatemail's answer with mine... you could do this
e <- new.env()
print.myClass <- function(x, ...) cat("<environment: ", environmentName(x), ">\n", sep="")
class(e) <- "myClass"
e
#<environment: >
attr(e, "name") <- "myEnv"
e
#<environment: myEnv>
According to the code used to print environments (./src/main/printutils.c
as of r66641), you can't get it to print as:
> e
<environment: myEnv>
Here's the relevant section of printutils.c
:
attribute_hidden
const char *EncodeEnvironment(SEXP x)
{
const void *vmax = vmaxget();
static char ch[1000];
if (x == R_GlobalEnv)
sprintf(ch, "<environment: R_GlobalEnv>");
else if (x == R_BaseEnv)
sprintf(ch, "<environment: base>");
else if (x == R_EmptyEnv)
sprintf(ch, "<environment: R_EmptyEnv>");
else if (R_IsPackageEnv(x))
snprintf(ch, 1000, "<environment: %s>",
translateChar(STRING_ELT(R_PackageEnvName(x), 0)));
else if (R_IsNamespaceEnv(x))
snprintf(ch, 1000, "<environment: namespace:%s>",
translateChar(STRING_ELT(R_NamespaceEnvSpec(x), 0)));
else snprintf(ch, 1000, "<environment: %p>", (void *)x);
vmaxset(vmax);
return ch;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With