Is there a way to throw an error instead of a warning?
22:30 01 Oct 2024

I am working on a test script of a package we are developing and I kinda got stuck with this. I have a function which takes multiple formula (I won't go into details..) and want to test if the function can return an error when formula has invalid covariates. Specifically I am stuck with this case where covariate is a factor but squared (I know it does not work).

simple example

xxx <- function(formula){
  ....
}

n <- as.factor(1:3)
formula <- ~ I(n ^ 2)
xxx(n)

and this returns a warning

Warning message:
In Ops.factor(n, 2) : ‘^’ not meaningful for factors

it is because of this

> I(n ^ 2)
[1] NA NA NA
Warning message:
In Ops.factor(n, 2) : ‘^’ not meaningful for factors

but because I(n^2) returns NAs with a warning not an error, function returns a error in unexpected place where it cannot process with NAs.

Can anyone help me with I(n^2) evaluations to stop when argument is invalid (this case, factor) and returns with an error instead of giving NAs and warning message?

Also, this function is a part of bigger function so the formula argument takes in a form of ~ + xxx + yyy.

r warnings