简短版:函数如何区分接收这两个输入?
value <- "asdf"
"asdf"
可复制的示例:假设我有一个寻找邪恶的函数,或者至少寻找字符串"evil"
library(stringr)
Find_Evil <- function(x) {
x <- str_to_lower(x)
if(str_detect(x, "evil")) {
message("Evil detected")
} else {
return(x)
}
}
该功能在检测输入中是否存在"evil"
时效果很好。
Find_Evil("this has some evil in it")
Evil detected
如果我还想检测变量名中是否包含evil
,该怎么办?这在不应该通过的时候可以解决。
sneaky_evil <- "sounds good but isn't"
Find_Evil(sneaky_evil)
[1] "sounds good but isn't"
我可以使用deparse(substitute())
检查变量名,但是如何首先检查某个东西是否是变量?我想要的是类似于下面的元代码的内容(无效:
Find_Evil <- function(x) {
x <- str_to_lower(x)
if (x is a variable) { # this is the part I need help on
x_name <- str_to_lower(deparse(substitute(sneaky_evil))) # convert value name to string
evil_name <- str_detect(x_name, "evil") # check name for evil
evil_x <- str_detect(x, "evil") # check contents for evil
if (sum(evil_name, evil_x) != 2) { # if either name or contents contains evil
message("evil detected")
} else {
return(x)
}
} else {
if (str_detect(x, "evil")) { # if x isn't a variable just check x (no name)
message("Evil detected")
} else {
return(x)
}
}
我们可以使用
library(stringr)
Find_Evil <- function(x) {
var_name <- deparse(substitute(x))
if(str_detect(var_name, "evil")) {
return("evil detected in variable")
}
x <- tolower(x)
if(str_detect(x, 'evil')) {
return("Evil detected in string")
}
else return(x)
}
sneaky_evil <- "sounds good but isn't"
Find_Evil(sneaky_evil)
#[1] "evil detected in variable"
sneaky_only <- "sounds good but isn't"
Find_Evil(sneaky_only)
#[1] "sounds good but isn't"
sneaky_only <- "sounds good but evil"
Find_Evil(sneaky_only)
#[1] "Evil detected in string"
可能类似这样会有所帮助:
Find_Evil <- function(x) {
var_type <- substitute(x)
var_name <- deparse(substitute(x))
if(grepl('evil', var_name) & is.name(var_type)) {
return("evil detected in variable")
}
x <- tolower(x)
if(grepl('evil', x)) {
return("Evil detected in string")
}
else return(x)
}
sneaky_evil <- "sounds good but isn't"
Find_Evil(sneaky_evil)
#[1] "evil detected in variable"
sneaky_only <- "sounds good but isn't"
Find_Evil(sneaky_only)
#[1] "sounds good but isn't"
sneaky_only <- "sounds good but evil"
Find_Evil(sneaky_only)
#[1] "Evil detected in string"
Find_Evil("sounds good but isn't")
#[1] "sounds good but isn't"
Find_Evil("sounds good but evil")
#[1] "Evil detected in string"