簡體   English   中英

為什么as.integer64(“”)返回0而不是NA_integer64_?

[英]Why does as.integer64(“”) return 0 instead of NA_integer64_?

鑒於空字符串的基本as.integer()強制是NA而沒有警告,如:

str( as.integer(c('1234','5678','')) ) # int [1:3] 1234 5678 NA -- no warning

我很難理解為什么bit64::as.integer64()在沒有警告的情況下bit64::as.integer64()為零:

library('bit64')
str( as.integer64(c('1234','5678','')) ) # integer64 [1:3] 1234 5678 0 -- no warning

更奇怪的是比較:

str( as.integer(c('1234','5678','', 'Help me Stack Overflow')) ) 
# int [1:4] 1234 5678 NA NA -- coercion warning

有:

str( as.integer64(c('1234','5678','', 'Help me Stack Overflow')) ) 
# integer64 [1:4] 1234 5678 0 NA -- no warning

我的解決方法失敗了:

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?

所以,我問:

  • 為什么會這樣?

  • 什么是最好的解決方法?

為什么會這樣

正如@ 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_;
}

當調用無效值(例如"""ABCD" strtoll("")strtoll("")返回零並顯示錯誤。 一個參考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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM