gggerald
gggerald

Reputation: 1

Create an error check for a function based on numeric data type?

I am trying to write a function that can show a specific error message, when I make a mistake. Does anyone know how to do this? Any help would be greatly appreciated.

For Example

newFunction <- function(a) {
for(i in 1:a) {
a <- i^2
print(a) 
}}

newFunction('five')

I would like to get an error message, such as "Stop! Variable is non-numerical"

How do I do this?

Upvotes: 0

Views: 33

Answers (1)

stevec
stevec

Reputation: 52238

You can check whether the input is numeric with is.numeric() and use stop() if it isn't

e.g.

if(!is.numeric(a)) {
  stop("Stop! Variable is non-numerical")
}

Upvotes: 1

Related Questions