Short version: How can a function differentiate between receiving these two inputs?
value <- "asdf"
"asdf"
A reproducible example:
Say I have a function that looks for evil, or at least for the string "evil"
library(stringr)
Find_Evil <- function(x) {
x <- str_to_lower(x)
if(str_detect(x, "evil")) {
message("Evil detected")
} else {
return(x)
}
}
The function works fine in detecting the presence of "evil" in its input.
Find_Evil("this has some evil in it")
Evil detected
What if I also want to detect whether or not a variable name has evil in it? This gets through when it shouldn't.
sneaky_evil <- "sounds good but isn't"
Find_Evil(sneaky_evil)
[1] "sounds good but isn't"
I can check a variable name using deparse(substitute()) but how do I check to see if something is a variable first? What I'd like is something along the lines of the meta-code below (doesn't work):
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)
}
}