我希望能够使用该deparse功能,如果我这样做
g = function(x) deparse(substitute(x))
Run Code Online (Sandbox Code Playgroud)
那么就可以了
R) g(test)
[1] "test"
Run Code Online (Sandbox Code Playgroud)
但如果我想测试 的参数是否g是character
h = function(x) {if(is.character(x)){return(x)}; deparse(substitute(x))}
R) h(test)
Error in h(test) : object 'test' not found
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况?我可以修复它吗?
编辑:从新复制R --vanilla
R version 2.15.2 (2012-10-26)
Platform: i386-w64-mingw32/i386 (32-bit)
locale:
[1] LC_COLLATE=English_United Kingdom.1252
[2] LC_CTYPE=English_United Kingdom.1252
[3] LC_MONETARY=English_United Kingdom.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
Run Code Online (Sandbox Code Playgroud)
问题中的代码正在尝试评估test不存在的变量 ,因此会出现错误。试试这个:
g = function(x) {
x.try <- try(x, silent = TRUE)
if (!inherits(x.try, "try-error") && is.character(x.try)) x.try
else deparse(substitute(x))
}
# test it out
if (exists("test")) rm(test)
g(test) # "test"
g("test") # "test"
test <- "xyz"
g(test) # "xyz"
g("test") # "test"
test <- 3
g(test) # "test"
g("test") # "test"
Run Code Online (Sandbox Code Playgroud)