2014-09-24 58 views
0

我试图将数据框(p2)中的一个因子(tickets_other)转换为整数。继将R帮助指导,以及来自其他其他方面的建议,该代码应工作:将因子强制转换为整数的问题

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

列不包含港定居,所以我得到一个警告:

Warning message: 
NAs introduced by coercion 

这很好,但是它强迫为数字后,它仍然读取的一个因素:(as.character())

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

如果我使用as.numeric同样的结果发生了:

as.numeric(as.character(p2$tickets_other)) 
Warning message: 
NAs introduced by coercion 
class(p2$tickets_other) 
[1] "factor" 
+0

请提供一些数据 – 2014-09-24 17:31:42

+0

这里命令'head(p2)'或'head(p2 $ tickets_other)'的输出结果。 – rnso 2014-09-24 17:34:37

+0

不看你的数据。我猜你需要'as.numeric(as.character(p2 $ tickets_other))' – Vlo 2014-09-24 17:53:30

回答

0

我修复了这个问题。这其实很简单。命令:

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

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

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

简单的错误,它回顾。感谢DMT的建议。

0

你这样做:

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

您正在阅读从p2$tickets_other(载体)的水平,然后将其转换为数字(仍然是一个向量),然后根据访问该矢量的索引值在p2$tickets_other

我无法想象这是你真正想要做的。

也许只是

as.numeric(p2$tickets_other) 

是你想要的吗?