Given that the base as.integer() coercion of the empty string is NA without warning, as in:
str( as.integer(c('1234','5678','')) ) # int [1:3] 1234 5678 NA -- no warning
I'm struggling to understand why bit64::as.integer64() coerces to zero without warning:
library('bit64')
str( as.integer64(c('1234','5678','')) ) # integer64 [1:3] 1234 5678 0 -- no warning
What's even stranger is to compare:
str( as.integer(c('1234','5678','', 'Help me Stack Overflow')) )
# int [1:4] 1234 5678 NA NA -- coercion warning
with:
str( as.integer64(c('1234','5678','', 'Help me Stack Overflow')) )
# integer64 [1:4] 1234 5678 0 NA -- no warning
My workaround for this fails miserably:
asInt64 <- function(s){
require(bit64)
ifelse(grepl('^\\d+$',s), as.integer64(s), NA_integer64_)
}
str(asInt64(c('1234','5678','', 'Help me Stack Overflow')) )
# num [1:4] 6.10e-321 2.81e-320 0.00 0.00
# huh?
So, I'm asking:
why does this happen?
what is the best workaround?
Why it happens
As @lukeA's comment points out, the source for
as.integer64.characteris:and
strtoll("")returns zero with an error when called on an invalid value such as""or"ABCD". One referencestrtollexample handles this like:So what I am trying to figure out now is why
*endpointeris evaluating to FALSE. (Stay tuned...)Workaround
Here's the workaround to mimic the behavior of base
as.integer:To see that this works: