我正在从不属于我的字符数据中形成一个 data.frame 控制(来自 API)。我希望结果变量得到他们的 最自然的类(class),无需大惊小怪。具体来说,我想要整数 变量,而不是数字,在适当的时候。
我正在从 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()
文档的相关位:“给定一个字符向量,它
尝试将其转换为逻辑、整数、数字或复数,并且
失败将其转换为因子,除非 as.is = TRUE。第一种
选择可以接受所有非缺失值的...向量
包含可选的空格后跟十进制常量
可表示为 R 整数或来自 na.strings 的值被转换为
整数。”
最佳答案
From reading the
type.convert()
docs, I'm surprised it does not produce integers when all the data could be represented as integer. Am I misreading that?
我想你可能是。
在某些情况下,将写为 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
关于r - 获取整数原子向量(相对于数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32345143/