首页 > 解决方案 > 在 R 中使用“NA”值在测试数据集中创建目标变量列

问题描述

我想结合测试和训练数据集。在此之前我必须添加一个新列来测试数据集以匹配训练数据集的列数。

我正在使用“NA”值在测试数据集中创建一个新列,这是我使用的代码:

test[,Item_Outlet_Sales := "NA"]

编译这段代码给了我这个错误:

Error in `:=`(Item_Outlet_Sales, "NA") : 
  Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").

标签: rerror-handlingdata.tabledata-manipulation

解决方案


您只需要将数据框转换为 data.table。

x[, X := NA]
Error in `:=`(X, NA) : 
Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").
z <- as.data.table(x)
z[, X := NA]

然后您可以看到添加了名为“X”的列。

在你的情况下,你只需要

test <- as.data.table(test)
test[,Item_Outlet_Sales := "NA"]

并使用 := 表示法添加新列。


推荐阅读