我怎样才能让这个deparse函数工作
如果我这样做,我希望能够使用deparse函数我怎样才能让这个deparse函数工作,r,R,如果我这样做,我希望能够使用deparse函数 g = function(x) deparse(substitute(x)) 那就好了 R) g(test) [1] "test" 但是如果我想测试g的参数是不是一个字符 为什么会发生这种情况?我能修复它吗 编辑:从一个新的R-香草复制 因为测试在全局环境中不存在。substitute不计算其参数,因此它不查找对象测试。character确实计算其参数,因此在找不到测试时抛出错误 如何解决问题取决于当对象不存在时,您希望函数做什么。如果希望它返
g = function(x) deparse(substitute(x))
那就好了
R) g(test)
[1] "test"
但是如果我想测试g的参数是不是一个字符
为什么会发生这种情况?我能修复它吗
编辑:从一个新的R-香草复制
因为测试在全局环境中不存在。substitute不计算其参数,因此它不查找对象测试。character确实计算其参数,因此在找不到测试时抛出错误
如何解决问题取决于当对象不存在时,您希望函数做什么。如果希望它返回对象名称,请执行以下操作:
h <- function(x) {
var <- deparse(substitute(x))
if(exists(var) && is.character(x)) x else var
}
因为测试在全局环境中不存在。substitute不计算其参数,因此它不查找对象测试。character确实计算其参数,因此在找不到测试时抛出错误
如何解决问题取决于当对象不存在时,您希望函数做什么。如果希望它返回对象名称,请执行以下操作:
h <- function(x) {
var <- deparse(substitute(x))
if(exists(var) && is.character(x)) x else var
}
问题中的代码试图计算一个不存在的变量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"
问题中的代码试图计算一个不存在的变量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"
你确定?你有没有试过从一个干净的会议?哦,来吧。。。我会把我的会议记录放进去你确定吗?你有没有试过从一个干净的会议?哦,来吧。。。我会把我的会话信息
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"