【问题标题】:Creating target variable column in test data set with "NA" values in R在 R 中使用“NA”值在测试数据集中创建目标变量列
【发布时间】:2018-09-25 10:38:54
【问题描述】:

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

我正在使用“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(":=").

【问题讨论】:

标签: r error-handling data.table data-manipulation


【解决方案1】:

您只需要将数据框转换为 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"]

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

【讨论】:

  • 或到位setDT(test)
【解决方案2】:
library(dplyr)    
test <- test %>% 
      mutate(
            Item_Outlet_Sales = NA
      )   

【讨论】:

    【解决方案3】:

    代码没问题,试试这个: test&lt;-data.table(test)

    【讨论】:

      猜你喜欢
      • 2013-04-02
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 2015-08-02
      相关资源
      最近更新 更多