I would like to build a function such as:
test <- function( fct = "default" ) {
# here test that fct is a string
# ...
}
in which it is tested that fct is a string of length one. Defining isSingleString() as:
isSingleString <- function(fct) { is.character(fct) & length(fct) == 1 }
seemed like a good idea. Thus:
test <- function( fct = "default" ) {
# here test that fct is a string
if (!isSingleString(fct)) stop ("error: not a string")
# ...
print("things are running smoothly!")
}
Using test("mean") and test("CI") works ok; test(mean) and and test(2) return the error as expected, but test(CI) crashes, saying that Error: object 'CI' not found.
What can I do to test the argument fct properly?
"", CI is treated as a symbol e.g. an object in your environment. If CI does not exist, you will get an error. By example, runningCI <- 2; test(CI)andCI <- "CI"; test(CI)works. So for your function, do you want it to treat anything insidetest()as literal?CIas a lazy-typing of"CI", I suggest that is rife with corner-cases and problems that are often not worth it in the end; or (2) a clear misunderstanding on our part for your intent to check not just the class and length of the argument, but if it exists at all. I think Edward's suggestion fortryCatchis appropriate in that second case, but frankly I think that level of resilience (a user supplying a non-existent symbol/name) may be over-engineering things.stopifnotand, as mentioned already,&&). You may want to consider ifNA_character_is valid input. Why would you want to catch an object-not-found error only to throw a different error message? That error is very clear.checkmatepackage. See here for details. In your case, something likeassert_character(fct, len = 1).object 'CI' not found?