gpt4 book ai didi

r - 使用 tidyverse 和 base R 删除列 - 区别

转载 作者:行者123 更新时间:2023-12-05 00:12:44 38 4
gpt4 key购买 nike

在尝试安装 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))

这最终出现以下错误:

Error in randomForest.default(x = select(Boston[train, ], -medv), y = select(Boston[train, : length of response must be the same as predictors In addition: Warning message: In randomForest.default(x = select(Boston[train, ], -medv), y = select(Boston[train, : The response has five or fewer unique values. Are you sure you want to do regression?



但是,当我用基数 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"] 之类的东西,这显然不起作用。

最佳答案

问题在于 randomForest 中的 y .它们需要是向量而不是 data.frames。

如果您使用 dplyr::select它总是返回一个data.frame。

str(dplyr::select(Boston, medv)
'data.frame': 506 obs. of 1 variable:
$ medv: num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

与通过基数 R 选择单列相比
str(Boston[, 14])
num [1:506] 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

要在选择 1 列时获得与 dplyr 相同的结果,您需要在 data.frame 单列选择中使用 drop = FALSE。
str(Boston[, 14, drop = FALSE])
'data.frame': 506 obs. of 1 variable:
$ medv: num 24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

为了让你的代码正确,你可以使用 as_vector来自 purrr强制包含 medv 的 data.frame成一个向量。
map_dbl(ps, ~mean(randomForest(x = dplyr::select(Boston[train,], -medv), 
y = as_vector(dplyr::select(Boston[train,], medv)),
xtest = dplyr::select(Boston[-train,], -medv),
ytest = as_vector(dplyr::select(Boston[-train,], medv)),
mtry = .x, ntree = 500)$test$mse))



[1] 22.36214 15.52031 13.24707 12.22685 12.32809 11.82220 11.91149 11.65336 12.05399 12.16599 12.63174 12.79196 12.41167

关于r - 使用 tidyverse 和 base R 删除列 - 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50075052/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com