Confirmation of function input in R

I want the error to interfere with the input value to make sure the user enters the correct choice. In this case, there are five options: "ns", "dl", "sv", "asv", "cs". I would like to check the use of input against them if none of them are present, then returns an error message and msg if the default null value is empty and send a message to the user. I tried to scan on a vector string, but that didn't work. Any suggestions are welcome.

method = "ns" if(method != scan(c("ns", "dl", "sv", "asv" ))) {"Invalid Value"} else {method = method} 
+6
source share
1 answer

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" 
+10
source

Source: https://habr.com/ru/post/955920/


All Articles