首页 文章

获取整数原子向量(与数字相对)

提问于
浏览
3

我正在从不受我控制的角色数据(来自API)中形成一个data.frame . 我希望得到的变量能够最简单地获得最自然的类 . 具体来说,在适当的时候,我想要整数变量,而不是数字 .

我正在从XML和一个属性中挖掘这些数据 - 让我们称之为 attA - 将整数表示为整数,即没有句点和尾随零 . 另一个属性 - 让我们称之为 attB - 更通常是有用且正确的,但总是呈现带有一个小数位的数字,即使它一致为零 . (请注意,数据也可能是字符!)

我的初始方法基于 attA 并通过 type.convert() 处理,但现在我想使用 attB . 通过阅读 type.convert() 文档,我很惊讶当所有数据都可以表示为整数时它不会产生整数 . 我误读了吗?关于如何在不对字符数据进行某些不正当处理的情况下获得我想要的任何建议?

attA <- c("1", "2")
str(type.convert(attA))
#>  int [1:2] 1 2

attB <- c("1.0", "2.0")
str(type.convert(attB))
#>  num [1:2] 1 2

unholy <- gsub("\\.0$", "", attB)
str(type.convert(unholy))
#>  int [1:2] 1 2

type.convert() docs的相关位:"Given a character vector, it attempts to convert it to logical, integer, numeric or complex, and failing that converts it to factor unless as.is = TRUE. The first type that can accept all the non-missing values is chosen... Vectors containing optional whitespace followed by decimal constants representable as R integers or values from na.strings are converted to integer."

2 回答

  • 1

    通过阅读type.convert()文档,我很惊讶当所有数据都可以表示为整数时它不会产生整数 . 我误读了吗?

    我想你可能会 .

    在某些情况下,将写为 123.0 的数字转换为 123 确实会改变其含义: 123.0 中的尾随零可以表示它表示的测量值比 123 (更高的精度)(例如最接近的十分之一)可能只是测量到最接近的整数值) . (See Wikipedia's article on significant figures for a fuller explanation.)所以 type.convert() 采用适当/保守的方法将 123.0 (实际上是 123. )视为表示数值而不是整数值 .

    作为解决方案,这样的事情怎么样?

    type.convert2 <- function(x) {
        x <- sub("(^\\d+)\\.0*$", "\\1", x)
        type.convert(x)
    }
    
    class(type.convert2("123.1"))
    # [1] "numeric"
    class(type.convert2("123.0"))
    # [1] "integer"
    class(type.convert2("123."))
    # [1] "integer"
    
    class(type.convert2("hello.0"))
    # [1] "factor"
    type.convert2("hello.0")
    # [1] hello.0
    # Levels: hello.0
    
  • 2

    一种方法是在强制转换为整数后对值进行测试,

    res <- type.convert(attB)
    if (isTRUE(all.equal((tmp <- as.integer(res)), res))) res <- tmp
    

    另一种可能是使用 trunc 来测试截断值 .

    type.convert 不会将字符串转换为整数,因为它在C中使用 strtol 函数,该函数在"."处停止 . 然后,在R源代码中,您会看到line,其中 res 是由 strtol 生成的转换后的字符串,

    if (*endp != '\0') res = NA_INTEGER;
    

    这意味着,如果整个字符串无效,那么它不是整数 .

相关问题