数据框值获取整数值而不是文本

时间:2019-04-10 07:08:10

标签: r string dataframe for-loop integer

这是我的数据:

require(HH)
data(ProfChal)
rowsCount = length(ProfChal$Question)
ProfChal$NEW = character(rowsCount)

看起来像这样:
HH ProfChal dataset

当我运行此循环时:

for (r in 1:rowsCount){
  ProfChal[r,"NEW"] = ProfChal[r,"Subtable"]
}

新列中包含整数:
Results table after running for loop - integers filled in

我想要的是 text 值,而不是 integers 。调试它使我感到困惑...

ProfChal[2,"Subtable"]返回[1] Employment sector
ProfChal[1,"NEW"] = "asdf"正常工作。

1 个答案:

答案 0 :(得分:2)

问题在于列Subtable是以factor而不是character的形式存储的。 您可以通过输入class(ProfChal[ ,"Subtable"])进行检查。

您可以使用as.character将此列转换为字符:

ProfChal[, "NEW"] = as.character(ProfChal[, "Subtable"])

还请注意,在此示例中不需要for循环。