Perhaps you are looking for %in% , and you can use it in strings:
myFun <- function(input=NULL) { Check <- c("ns", "dl", "sv", "asv", "cs") if (is.null(input)) { message("No 'input' value defined. Using 'ns' by default") input <- "ns" } if (!input %in% Check) stop("Invalid 'input' value") input } myFun() # No 'input' value defined. Using 'ns' by default # [1] "ns" myFun("sv") # [1] "sv" myFun("vs") # Error in myFun("vs") : Invalid 'input' value
Not knowing exactly what you want to do, you can also look at the switch function.
myFun2 <- function(input = NULL) { Check <- c("ns", "dl", "sv", "asv", "cs") if (is.null(input)) { message("No 'input' value defined. Using 'ns' by default") input <- "ns" } switch(input, ns = "Whoo", dl = "Whee", sv = "Whaa", asv = "Whii", cs = "Whuu", stop("You did not say the magic word")) } myFun2() # No 'input' value defined. Using 'ns' by default # [1] "Whoo" myFun2("sv") # [1] "Whaa" myFun2("sc") # Error in myFun2("sc") : You did not say the magic word
Update: match.arg
By popular demand, the match.arg version is also given above, but note that you no longer need to enter a message saying that you are not using a magic word, and instead you need to set an automatically generated descriptive and useful error message, This is not fun...
myFun3 <- function(input=NULL) { Check <- c("ns", "dl", "sv", "asv", "cs") if (is.null(input)) { message("No 'input' value defined. Using 'ns' by default") input <- "ns" } input <- match.arg(input, Check) switch(input, ns = "Whoo", dl = "Whee", sv = "Whaa", asv = "Whii", cs = "Whuu") } myFun3() # No 'input' value defined. Using 'ns' by default # [1] "Whoo" myFun3("sv") # [1] "Whaa" myFun3("sc") # Error in match.arg(input, Check) : # 'arg' should be one of "ns", "dl", "sv", "asv", "cs"