我有一个csv文件(298行和24列),我想创建一个决策树来预测“salary”这一列。我已经下载了tree包并通过库函数添加了它。
但是当我尝试创建决策树时:
model<-tree(salary~.,data)
我得到了如下错误:
*Error in tree(salary ~ ., data) : factor predictors must have at most 32 levels*
这是怎么回事?数据如下:
Name bat hit homeruns runs1 Alan Ashby 315 81 7 242 Alvin Davis 479 130 18 663 Andre Dawson 496 141 20 65...team position putout assists errors1 Hou. C 632 43 102 Sea. 1B 880 82 143 Mon. RF 200 11 3salary league87 team871 475 N Hou.2 480 A Sea.3 500 N Chi.
这是str(data)的值:
‘data.frame’: 263 obs. of 24 variables: $ Name : Factor w/ 263 levels “Al Newman”,”Alan Ashby”,..: 2 7 8 10 6 1 13 11 9 3 …
$ bat : int 315 479 496 321 594 185 298 323 401 574 …
$ hit : int 81 130 141 87 169 37 73 81 92 159 …
$ homeruns : int 7 18 20 10 4 1 0 6 17 21 …
$ runs : int 24 66 65 39 74 23 24 26 49 107 …
$ runs.batted : int 38 72 78 42 51 8 24 32 66 75 …
$ walks : int 39 76 37 30 35 21 7 8 65 59 …
$ years.in.major.leagues : int 14 3 11 2 11 2 3 2 13 10 …
$ bats.during.career : int 3449 1624 5628 396 4408 214 509 341 5206 4631 …
$ hits.during.career : int 835 457 1575 101 1133 42 108 86 1332 1300 …
$ homeruns.during.career : int 69 63 225 12 19 1 0 6 253 90 …
$ runs.during.career : int 321 224 828 48 501 30 41 32 784 702 …
$ runs.batted.during.career: int 414 266 838 46 336 9 37 34 890 504 …
$ walks.during.career : int 375 263 354 33 194 24 12 8 866 488 …
$ league : Factor w/ 2 levels “A”,”N”: 2 1 2 2 1 2 1 2 1 1 …
$ division : Factor w/ 2 levels “E”,”W”: 2 2 1 1 2 1 2 2 1 1 …
$ team : Factor w/ 24 levels “Atl.”,”Bal.”,..: 9 21 14 14 16 14 10 1 7 8 …
$ position : Factor w/ 23 levels “1B”,”1O”,”23″,..: 10 1 20 1 22 4 22 22 13 22 …
$ putout : int 632 880 200 805 282 76 121 143 0 238 …
$ assists : int 43 82 11 40 421 127 283 290 0 445 …
$ errors : int 10 14 3 4 25 7 9 19 0 22 …
$ salary : num 475 480 500 91.5 750 …
$ league87 : Factor w/ 2 levels “A”,”N”: 2 1 2 2 1 1 1 2 1 1 …
$ team87 : Factor w/ 24 levels “Atl.”,”Bal.”,..: 9 21 5 14 16 13 10 1 7 8 …
回答:
问题几乎可以肯定是你将名称变量包含在模型中,因为它有太多的因子水平。从方法论的角度来看,我也建议移除它,但这可能不是讨论这个话题的地方。试试以下方法:
train <- datatrain$Name <- NULLmodel<-tree(salary~.,train)