将因素强制转换成整数的问题

时间:2014-09-24 17:27:48

标签: r coercion

我正在尝试将数据框(p2)中的因子(tickets_other)转换为整数。遵循R帮助指南以及其他人的其他建议,此代码应该有效:

as.numeric(levels(p2$tickets_other))[p2$tickets_other]

该列确实包含NA,因此我收到警告:

Warning message:
NAs introduced by coercion

哪个好,但在将其强制转换为数字之后,它仍然是一个因素:

class(p2$tickets_other)
[1] "factor"

如果我使用as.numeric(as.character。()):

,会出现同样的结果
as.numeric(as.character(p2$tickets_other))
Warning message: 
NAs introduced by coercion 
class(p2$tickets_other)
[1] "factor"

2 个答案:

答案 0 :(得分:0)

您正在做:

as.numeric(levels(p2$tickets_other))[p2$tickets_other]

您正在从p2$tickets_other(向量)读取级别,然后将它们转换为数字(仍为向量),然后根据p2$tickets_other

我无法想象这就是你真正想做的事情。

也许只是

as.numeric(p2$tickets_other)

是你想要的吗?

答案 1 :(得分:0)

我解决了这个问题。实际上非常简单。命令:

as.numeric(levels(p2$tickets_other))[p2$tickets_other]

是正确的,但我未能存储结果:

p2$tickets_other <- as.numeric(levels(p2$tickets_other))[p2$tickets_other]

简单的错误,它回想起来。感谢DMT提出的建议。