首页 > 解决方案 > 二元运算符的随机森林错误非数字参数

问题描述

我在 R studio 中学习教程,我无法在 https://github.com/dataprofessor/rshiny_freecodecamp/blob/main/3-play-golf/app.R编译代码

以下代码行不起作用,我不明白为什么。请帮忙。

model <- randomForest(play ~ ., data = weather, ntree = 500, mtry = 4, importance = TRUE)# Save model to RDS file

y - ymean 中的错误:二元运算符的非数字参数此外:警告消息:1:在 randomForest.default(m, y, ...) 中:
响应具有五个或更少的唯一值。您确定要进行回归吗?2:在 mean.default(y) 中:参数不是数字或逻辑:返回 NA

标签: rrandom-forest

解决方案


您被 R 4.x0 和 R3.x 处理 data.frames 创建的方式的不同所吸引。在 R4.x 之前以及创建上述示例时,字符串会自动转换为因子。这在 R4.0 中的更改是默认设置是在创建 data.frame 时不将字符串转换为因子。

解决您的代码:设置stringsAsFactorsTRUE

# Read data
url <- "https://raw.githubusercontent.com/dataprofessor/data/master/weather-weka.csv"
weather <- read.csv(file = url, stringsAsFactors = TRUE)

# Build model
model <- randomForest(play ~ ., data = weather, ntree = 500, mtry = 4, importance = TRUE)

或者自己创建一个因子:

# Read data
url <- "https://raw.githubusercontent.com/dataprofessor/data/master/weather-weka.csv"
weather <- read.csv(file = url)

weather$play <- as.factor(weather$play)

# Build model
model <- randomForest(play ~ ., data = weather, ntree = 500, mtry = 4, importance = TRUE)

推荐阅读