So I was starting to make my code
myplot2=function(d,a){
if(!(is.data.frame(d)))
stop("Error:Is not dataframe")
if(a!= 1 || a!= 2){
stop("Error:Has to be one or two")
}
}
My problem is that this happens when i actually plug in 1 or into the data.
> myplot2(patients,1)
Error in myplot2(patients, 1) : Error:Has to be one or two
> myplot2(patients,2)
Error in myplot2(patients, 2) : Error:Has to be one or two
Why is my validity check failing to work properly?
CodePudding user response:
Rather than writing your own validity checks, another option is to make use of one of the available R packages. For example, using assertthat
:
library(assertthat)
myplot2 <- function(d, a) {
assert_that(is.data.frame(d))
assert_that(length(a) == 1 & !a %in% 1:2)
"all good"
}
# Examples
myplot2(NULL, 4)
# Error: d is not a data frame
myplot2(mtcars, 1)
# Error: length(a) == 1 & !a %in% 1:2 is not TRUE
myplot2(mtcars, 0)
# [1] "all good"