r - 为什么 R 会使用 "L"后缀来表示整数?

标签 r parsing integer semantics

在 R 中,我们都知道在我们想要确保我们正在处理一个整数以使用 "L" 指定它的时候很方便。像这样的后缀:

1L
# [1] 1

如果我们没有明确告诉 R 我们想要一个整数,它会假设我们打算使用 numeric数据类型...
str( 1 * 1 )
# num 1
str( 1L * 1L )
# int 1

为什么“L”是首选后缀,例如为什么不是“I”?有历史原因吗?

另外,为什么 R 允许我做(有警告):
str(1.0L)
# int 1
# Warning message:
# integer literal 1.0L contains unnecessary decimal point 

但不是..
str(1.1L)
# num 1.1
#Warning message:
#integer literal 1.1L contains decimal; using numeric value 

我希望两者都返回错误。

最佳答案

为什么使用“L”作为后缀?
我从未见过它被写下来,但我总结起来有两个原因:

  • 因为 R 处理可以使用
    后缀"i"这与 "I" 太相似了
  • 由于 R 的整数是 32 位长整数,因此“L”似乎是指代这种数据类型的合理简写。

  • 长整数可以取的值取决于字长。 R 本身不支持字长为 64 位的整数。 R 中的整数的字长为 32 位并带有符号,因此范围为 −2,147,483,6482,147,483,647 .较大的值存储为 double .
    This wiki page有关于常见数据类型、它们的常规名称和范围的更多信息。
    还有来自 ?integer

    Note that current implementations of R use 32-bit integers for integer vectors, so the range of representable integers is restricted to about +/-2*10^9: doubles can hold much larger integers exactly.



    为什么 1.0L 和 1.1L 返回不同的类型?
    原因1.0L1.1L将返回不同的数据类型是因为为 1.1 返回一个整数将导致信息丢失,而对于 1.0它不会(但您可能想知道您不再有浮点数字)。这段代码(函数 /src/main/gram.c:4463-4485 的一部分)被词法分析器 ( NumericValue() ) 深深埋没,它实际上创建了一个 int来自 double 的数据类型以 ascii 为后缀的输入 "L" :
    /* Make certain that things are okay. */
    if(c == 'L') {
    double a = R_atof(yytext);
    int b = (int) a;
    /* We are asked to create an integer via the L, so we check that the
       double and int values are the same. If not, this is a problem and we
       will not lose information and so use the numeric value.
    */
    if(a != (double) b) {
        if(GenerateCode) {
        if(seendot == 1 && seenexp == 0)
            warning(_("integer literal %s contains decimal; using numeric value"), yytext);
        else {
            /* hide the L for the warning message */
            *(yyp-2) = '\0';
            warning(_("non-integer value %s qualified with L; using numeric value"), yytext);
            *(yyp-2) = (char)c;
        }
        }
        asNumeric = 1;
        seenexp = 1;
    }
    }
    

    关于r - 为什么 R 会使用 "L"后缀来表示整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24350733/

    相关文章:

    javascript - Javascript 中与 64 位整数的按位 AND

    r - 更改 ROC 图表的比例

    r - "The following object is masked from ' 包 :xxx'"mean? 是什么意思

    integer - 如何关闭整数溢出保护?

    android - 如何在 Android 中解析 JSON?

    将字符串转换为特定的日期格式

    java - 将 BigDecimal 转换为 Integer

    r - 如何解决 r 中的 'argument x is empty' 错误(Shiny Web 应用程序)

    r - data.table 后端的 dplyr 错误 [在 dplyr 0.4.3 或更早版本中]

    parsing - Elasticsearch无法使用自定义格式解析日期