简体   繁体   中英

Convert an R container name to character

How to convert a container name to a character since I got a error using the following code:

tenv = new.env()
evalq({    }, tenv)

y = function(myEnv) {
  print(as.character(myEnv))
}

y(tenv)

Error in as.character(myEnv) :
cannot coerce type 'environment' to vector of type 'character' 

If you just want to grab the name of the object passed to the myEnv argument, then one common idiom is deparse(substitute( )) . The function can be written as:

y <- function(myEnv) {
  deparse(substitute(myEnv))
}

which in use gives

> tenv = new.env()
> evalq({    }, tenv)
> y(tenv)
[1] "tenv"

[Note I don't explicitly print the result of deparse(substitute( )) , I just return it and leave the printing up to the R environment]

Another way to do this is to grab the matched function call with match.call() and then extract from the resulting language object the bit you want. For example:

yy <- function(myEnv) {
  .call <- match.call()
  .call[[2]]
}

which in use gives

> yy(tenv)
tenv
> yy(myEnv = tenv)
tenv

You cannot convert a "container" (environment) to a character string because an environment does not posses such a property. If you want the name of the variable where the environment is stored and was passed as argument to function y , then use the solution proposed by @Gavin above.

OTOH, if you want to dump the environment contents, then use this:

y = function(myEnv) {
  print(as.list(myEnv))
}

BTW, I must point out that I don't understand why do you run evalq({ }, tenv) . It doesn't change the environment. Try the following (after running your commands):

> uenv <- new.env()
> identical(as.list(uenv),as.list(tenv))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM