如何使用以下代码收到错误,将容器名称转换为字符:
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'
答案 0 :(得分:2)
如果您只想获取传递给myEnv
参数的对象的名称,那么一个常见的习语是deparse(substitute( ))
。该函数可写为:
y <- function(myEnv) {
deparse(substitute(myEnv))
}
正在使用
> tenv = new.env()
> evalq({ }, tenv)
> y(tenv)
[1] "tenv"
[注意我没有明确print
deparse(substitute( ))
的结果,我只是将其返回并将打印保留到R环境中]
另一种方法是使用match.call()
获取匹配的函数调用,然后从结果语言对象中提取所需的位。例如:
yy <- function(myEnv) {
.call <- match.call()
.call[[2]]
}
正在使用
> yy(tenv)
tenv
> yy(myEnv = tenv)
tenv
答案 1 :(得分:0)
您无法将“容器”(环境)转换为字符串,因为环境不具备此类属性。如果您想要存储环境的变量名称并作为参数传递给函数y
,那么请使用上面@Gavin提出的解决方案。
OTOH,如果要转储环境内容,请使用:
y = function(myEnv) {
print(as.list(myEnv))
}
顺便说一句,我必须指出,我不明白为什么要运行evalq({ }, tenv)
。它不会改变环境。尝试以下操作(运行命令后):
> uenv <- new.env()
> identical(as.list(uenv),as.list(tenv))