eval(predvars、data、env)中出错:对象';示例';在随机林函数中找不到
我只是在玩一个随机森林,但我似乎有一个问题。当我尝试使用eval(predvars、data、env)中出错:对象';示例';在随机林函数中找不到,r,eval,random-forest,R,Eval,Random Forest,我只是在玩一个随机森林,但我似乎有一个问题。当我尝试使用randomForest()函数时,它返回错误:eval(predvars,data,env)中的错误:找不到对象“180018R”。下面是最新(相关)的代码行,后面是structure()输出 install.packages("randomForest") # Random forest data <- as.data.frame(pattern_mat) str(data) # Response variable is "
randomForest()
函数时,它返回错误:eval(predvars,data,env)中的错误:找不到对象“180018R”
。下面是最新(相关)的代码行,后面是structure()
输出
install.packages("randomForest")
# Random forest
data <- as.data.frame(pattern_mat)
str(data)
# Response variable is "Response" Column 313
data$Response <- as.factor(data$Response)
table(data$Response)
### Data Partition
set.seed(123)
ind <- sample(2, nrow(data), replace=TRUE, prob=(c(0.7, 0.3)))
train <- data[ind==1,]
test <- data[ind==2,]
### Random Forest
library(randomForest)
set.seed(222)
rf <- randomForest(Response~., data = train)
因此,您可以看到错误:eval(predvars,data,env)中的错误:未找到对象“180018R”
提到的180018R,它是第一列的名称
有人知道该怎么做吗?就我所知,问题是列的名称以数字开头,这不是R中的最佳做法(尽管允许),我猜randomForest没有正确地使用
~。
语法处理它
尝试重命名所有列,使它们以一些通用字母开头,如V
,然后查看函数现在是否工作。这里有一个可重复的例子来说明这一点
set.seed(1)
data <- data.frame(x = rbinom(100, 1, 0.5))
data$`180018R` <- data$x
data$x <- NULL
data$Response <- as.factor(rbinom(100, 1, 0.2))
table(data$Response)
### Demonstrating error
library(randomForest)
set.seed(222)
rf <- randomForest(Response~., data = data)
# Produces error as in the original example
# Fixing the issue by adding a character to the column names except response
data2 <- data
response_col <- which(colnames(data2) == "Response")
colnames(data2)[-response_col] <- paste0( "V", colnames(data2)[-response_col])
set.seed(222)
rf <- randomForest(Response ~ ., data = data2)
# Runs with no issue
set.seed(1)
数据哇!谢谢你的清晰解释和回答!它工作得很好。如果您不想为自己的代码重命名可疑变量而烦恼,请尝试gatitor::clean_names
set.seed(1)
data <- data.frame(x = rbinom(100, 1, 0.5))
data$`180018R` <- data$x
data$x <- NULL
data$Response <- as.factor(rbinom(100, 1, 0.2))
table(data$Response)
### Demonstrating error
library(randomForest)
set.seed(222)
rf <- randomForest(Response~., data = data)
# Produces error as in the original example
# Fixing the issue by adding a character to the column names except response
data2 <- data
response_col <- which(colnames(data2) == "Response")
colnames(data2)[-response_col] <- paste0( "V", colnames(data2)[-response_col])
set.seed(222)
rf <- randomForest(Response ~ ., data = data2)
# Runs with no issue