1

I'm writing a function that catches conversion errors when a value is coerced to NA. It seems like the base conversion functions are inconsistent in returning warnings.

> as.numeric("a")
[1] NA
Warning message:
NAs introduced by coercion 

However, the warning is not shown when converting to logical:

> as.logical("a")
[1] NA

My question: Is there a way to make the warning explicit when a string cannot be converted to logical?

I have looked into rlang::as_logical(), but it returns an error instead of a warning, that I'd like to avoid if possible.

LyzandeR
  • 37,047
  • 12
  • 77
  • 87
Tamas Nagy
  • 1,001
  • 12
  • 22

2 Answers2

2

You can use options(warn =. For example:

options(warn=1, error=NULL)

to get a warning.

I typically handle this by promoting warnings to errors for the relevant part of the code.

For example:

options(warn=2, error=NULL)
as.logical(x)

Error: (list) object cannot be coerced to type 'logical'

You can also easily reset it like this options(warn=0, error=NULL)

Related: Breaking loop when "warnings()" appear in R

Hack-R
  • 22,422
  • 14
  • 75
  • 131
  • 1
    Thanks a lot, that seems to do the trick! I'd like to get it as a warning though, so I'm using `options(warn = 1)` – Tamas Nagy Jul 05 '18 at 15:53
  • @TamasNagy Great! Glad it helped. Sorry I misunderstood that you wanted an error rather than a warning. I can update it as such. – Hack-R Jul 05 '18 at 16:01
  • Finally, I went with `rlang::as_logical`, and handled failed conversions as errors instead of warnings, but this is still a good answer! – Tamas Nagy Jul 09 '18 at 11:45
1

You can make your own function about this:

as.logical2 <- function(x) {

  if (is.na(x)) return(x)
  out <- as.logical(x)
  #if there is an NA, you can issue a warning
  if (is.na(out)) warning('NAs introduced by coercion')
  out

}

as.logical2('a')
#[1] NA
#Warning message:
#In as.logical2("a") : NAs introduced by coercion
LyzandeR
  • 37,047
  • 12
  • 77
  • 87