【发布时间】:2018-04-28 09:37:28
【问题描述】:
在尝试适应 randomForest 并使用 select 按名称选择/删除数据框列时,我最终遇到了一个奇怪的行为:
library(MASS)
library(dplyr)
library(purrr)
library(randomForest)
train = base::sample(1:nrow(Boston), nrow(Boston)/2)
glimpse(Boston)
p <- ncol(Boston) - 1
ps <- 1:p
map_dbl(ps, ~mean(randomForest(x = select(Boston[train,], -medv),
y = select(Boston[train,], medv),
xtest = select(Boston[-train,], -medv),
ytest = select(Boston[-train,], medv),
mtry = .x, ntree = 500)$test$mse))
这最终出现以下错误:
randomForest.default(x = select(Boston[train, ], -medv), y = select(Boston[train, : 响应长度必须与预测变量相同 另外:警告信息: 在 randomForest.default(x = select(Boston[train, ], -medv), y = select(Boston[train, : 响应具有五个或更少的唯一值。您确定要进行回归吗?
但是,当我用基数 R 定义 x、y、xtest、ytest 时,公式有效:
map_dbl(ps, ~mean(randomForest(x = Boston[train, -14],
y = Boston[train, 14],
xtest = Boston[-train, -14],
ytest = Boston[train, 14],
mtry = .x, ntree = 500)$test$mse))
[1] 119.9225 132.5212 136.7131 139.7398 142.9167 144.2151 145.0587 146.9056 148.7087 148.1903 150.3910 [12] 151.5579 151.2323
所以我检查了这两种不同的子集化数据集的方法是否给出了相同的结果......然后做。
all(select(Boston[train,], -medv) == Boston[train, -14])
all(select(Boston[train,], medv) == Boston[train, 14])
all(select(Boston[-train,], -medv) == Boston[-train, -14])
all(select(Boston[-train,], medv) == Boston[-train, 14])
所有这些结果都是TRUE。为什么使用select 的第一个子集方法最终会在randomForest 模型中出现错误?使用他们的名字删除列的另一种方法是什么? (类似于Boston[,-"medv"] 显然不起作用。
【问题讨论】:
-
确保您使用的是来自
dplyr包的select函数,而不是来自MASS包的函数。 -
你确定有一个名为“train”的变量吗?我运行您的代码并收到以下错误:
[.data.frame(Boston, train, -14) 中的错误:找不到对象“火车” -
@ScipioneSarlo,用
train定义编辑,@www 是的,我用dpyr::select检查过