为什么会发生
正如@lukeA 的评论所指出的,来源as.integer64.character
是:
SEXP as_integer64_character(SEXP x_, SEXP ret_){
long long i, n = LENGTH(ret_);
long long * ret = (long long *) REAL(ret_);
const char * str;
char * endpointer;
for(i=0; i<n; i++){
str = CHAR(STRING_ELT(x_, i)); endpointer = (char *)str; // thanks to Murray Stokely 28.1.2012
ret[i] = strtoll(str, &endpointer, 10);
if (*endpointer)
ret[i] = NA_INTEGER64;
}
return ret_;
}
并strtoll("")
在调用无效值(例如""
or )时返回零并出错"ABCD"
。一个参考strtoll
示例如下处理:
/* If the result is 0, test for an error */
if (result == 0)
{
/* If a conversion error occurred, display a message and exit */
if (errno == EINVAL)
{
printf("Conversion error occurred: %d\n", errno);
exit(0);
}
/* If the value provided was out of range, display a warning message */
if (errno == ERANGE)
printf("The value provided was out of range\n");
}
所以我现在想弄清楚的是为什么*endpointer
评估为 FALSE。(敬请关注...)
解决方法
这是模仿 base 行为的解决方法as.integer
:
library(bit64)
charToInt64 <- function(s){
stopifnot( is.character(s) )
x <- as.integer64(s)
# as.integer64("") unexpectedly returns zero without warning.
# Overwrite this result to return NA without warning, similar to base as.integer("")
x[s==""] <- NA_integer64_
# as.integer64("ABC") unexpectedly returns zero without warning.
# Overwrite this result to return NA with same coercion warning as base as.integer("ABC")
bad_strings <- grepl('\\D',s) # thanks to @lukeA for the hint
if( any(bad_strings) ){
warning('NAs introduced by coercion')
x[bad_strings] <- NA_integer64_
}
x
}
要查看这是否有效:
test_string <- c('1234','5678','', 'Help me Stack Overflow')
charToInt64(test_string) # returns int64 [1] 1234 5678 <NA> <NA> with warning
charToInt64(head(test_string,-1)) # returns int64 [1] 1234 5678 <NA> without warning