0

我正在尝试将数据帧(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"
4

2 回答 2

0

我解决了这个问题。其实很简单。命令:

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

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

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

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

于 2014-09-25T18:22:22.920 回答
0

你正在做的:

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

您正在从p2$tickets_other(向量)读取级别,然后将它们转换为数字(仍然是向量),然后根据中的值访问该向量的索引p2$tickets_other

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

也许只是

as.numeric(p2$tickets_other)

是你想要的吗?

于 2014-09-24T17:53:18.513 回答