I am trying to do something relatively simple. I am trying to come up with a regression function using the lm() function and get the diagnostics.
Now the input for the lm() function is one which has a formula class.
How can a function be designed so as to test if the input is formula, stop and throw an error if it is not?
You can use class function to check whether an object is a formula or not
> fo <- y ~ x1*x2 # this is formula class
> stopifnot(class(fo)=="formula")
>
> fo <- 1
> stopifnot(class(fo)=="formula") # this not a formula
Error: class(fo) == "formula" is not TRUE
You can also define a function to test whether an object is a formula
> is.formula <- function(x){
class(x)=="formula"
}
>
> is.formula( y ~ x1*x2)
[1] TRUE
> is.formula(2)
[1] FALSE
If you want to write a custom error message you can proceed as follows (thanks to nico)
formula.test <- function(x){
ifelse( class(x)=="formula",
"This is a formula, you can go ahead!",
stop("This is not a formula, we must stop here."))
}
formula.test(y ~ x1*x2) # this is OK
formula.test("a") # stops execution and throws an error
formula.test(1) # stops execution and throws an error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With