R:[[。data.frame](框架,预测变量)中的决策树错误:未定义的列已选中

时间:2019-02-28 03:05:42

标签: r machine-learning tree decision-tree

m = matrix(rnorm(120, 100, 10), nrow = 20, ncol = 6) %>%
  data.frame()

indx = 1:(0.8*nrow(m))

colnames(m) = c('True', 1:(ncol(m)-1))

tree(True~., data = m, subset = indx)

使用上述代码构建决策树模型时,出现以下错误:

[.data.frame(框架,预测变量)中的错误:未定义的列已选中

列名中的错误?列名1:5确实具有含义,所以我可能不会轻易更改,还有另一种方法可以使它起作用吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

这确实与您的列名(R doesn't like column names that are numbers)有关;如果我们更改列名,错误就会消失

# Sample data.frame
set.seed(2018)
df <- setNames(as.data.frame(replicate(6, rnorm(20, 100, 10))), c("True", paste0("Var", 1:5)))
df
#        True      Var1      Var2      Var3      Var4      Var5
#1   95.77016 112.63864  96.40558 108.35183  86.35395 103.70908
#2   84.50122 102.50198  87.00464 105.89023 116.49011 106.73337
#3   99.35571 102.58195  91.30130 101.70094  92.20744  92.77447
#4  102.70881 117.85534 110.54362  95.62828 109.83104  94.29125
#5  117.35284  87.80294  98.51360  99.19792 105.05784  97.30385
#6   97.35289  97.59878 110.18077  90.72457  83.00285 108.04330
#7  120.99471  89.41338  92.78413 115.18867 125.97463  87.78891
#8  108.63351 104.19409  92.21222 100.85730  95.77344 110.74260
#9   93.89413  97.29043  93.81834 121.52795  92.66463 106.51900
#10 106.37056  93.68175 116.05205  86.34069 102.75945 101.69782
#11  93.56965  97.71588  94.12557 103.45906  90.17478  94.36445
#12  89.69971 111.78680  94.72556 105.65181 106.54766  79.04253
#13 107.12481  97.33727 105.96021  99.93902 114.74087 104.90003
#14  95.54228 105.28141  87.28688  95.61219 102.12982 105.78960
#15 102.48980  82.31341  97.98745 106.88891  84.50630  95.60654
#16  89.25806  95.10209 104.55634  95.00581 102.77174 102.21734
#17  81.72738 114.10522  90.65173  81.31385 109.83210  82.33406
#18 100.15492  89.24736 127.28318 107.43425 107.59388  90.73533
#19  83.15639 102.92395 103.46645  99.10825  93.42645 129.55945
#20 102.04468  97.93336  93.62290 110.81164 109.22904 102.45278

library(tree)
tr <- tree(True ~ ., data = df)
#node), split, n, deviance, yval
#      * denotes terminal node
#
#1) root 20 2089.0  98.59
#  2) Var1 < 94.3919 5  340.1 109.50 *
#  3) Var1 > 94.3919 15  958.3  94.96
#    6) Var3 < 99.5236 6  346.3  91.62 *
#    7) Var3 > 99.5236 9  501.0  97.18 *

plot(tr)
text(tr)

enter image description here