rnorouzian
rnorouzian

Reputation: 7517

Modifying the error message from a `stop()` call in R

In my stop call below, I get a message that is like:

Error: cname not found in the 'data'.hhk not found in the 'data'.

I was wondering if there is a way for the message to look like:

'cname', 'hhk' not found in the 'data'.

Is this possible in Base R?

vars = c("cname", "hhk")
a = 1
if(a) stop(paste(vars, "not found in the 'data'."))

Current Error message: Error: cname not found in the 'data'.hhk not found in the 'data'.
Desired Error message: 'cname', 'hhk' not found in the 'data'.

Upvotes: 1

Views: 210

Answers (3)

akrun
akrun

Reputation: 887168

We can use stopifnot

stopifnot(a)

Or with glue

if(a) stop(glue::glue("{toString(vars)} not found in the data"))
#Error: cname, hhk not found in the data

Upvotes: 2

Dan Kennedy
Dan Kennedy

Reputation: 430

You can do this using two paste commands:

if(a) stop("'",paste(paste(vars,collapse = "', '",sep = ""), "' not found in the 'data'.",sep = ""))
Error: 'cname', 'hhk' not found in the 'data'.

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388982

Collapse vars into one string :

vars = c("cname", "hhk")
a = 1
if(a) stop(paste(toString(vars), "not found in the 'data'."))
#Error: cname, hhk not found in the 'data'.

Upvotes: 3

Related Questions