【问题标题】:Error in eval(predvars, data, env) : object 'Example' not found in RandomForest functioneval 中的错误(predvars,data,env):在 RandomForest 函数中找不到对象“示例”
【发布时间】:2020-05-07 01:15:30
【问题描述】:

我只是在玩随机森林,但我似乎遇到了问题。当我尝试使用randomForest() 函数时,它返回错误:Error in eval(predvars, data, env) : object '180018R' not found。这是最新的(相关)代码行,后面是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)

结构信息 *我已经缩短了输出,因为它是不必要的。

> str(train)
'data.frame':   145 obs. of  313 variables:
 $ 180018R : num  1 0 0 0 0 0 0 0 0 0 ...
 $ 217220R : num  1 0 0 0 0 0 0 0 0 0 ...
 $ 217300R : num  1 0 0 0 0 0 0 0 0 0 ...
 $ 281722R : num  0 1 1 1 1 1 1 1 1 0 ...
 $ 681714R : num  0 1 1 1 1 1 1 1 1 0 ...
 $ 281730R : num  0 1 1 1 1 1 1 1 1 0 ...
 $ 681715R : num  0 1 1 1 1 1 1 1 1 0 ...
 $ 411113  : num  0 0 0 0 0 0 0 0 0 1 ...
 $ 478105  : num  0 0 0 0 0 0 0 0 0 1 ...
     :        :   : : : : : : : : : :
     :        :   : : : : : : : : : :
     :        :   : : : : : : : : : :
 $ 641112  : num  0 0 0 0 0 0 0 0 0 0 ...
 $ 641170  : num  0 0 0 0 0 0 0 0 0 0 ...
 $ 641370  : num  0 0 0 0 0 0 0 0 0 0 ...
 $ 641611  : num  0 0 0 0 0 0 0 0 0 0 ...
 $ 645342  : num  0 0 0 0 0 0 0 0 0 0 ...
  [list output truncated]

所以你可以看到错误:Error in eval(predvars, data, env) : object '180018R' not found 提到 180018R 这是第一列的名称。

有人知道该怎么做吗?

【问题讨论】:

    标签: r eval random-forest


    【解决方案1】:

    据我所知,问题在于以数字开头的列名,这不是 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
    

    【讨论】:

    • 哇!感谢您的清晰解释和回答!效果很好。
    • 如果您不想为自己的代码重命名可疑变量而烦恼,请尝试janitor::clean_names
    猜你喜欢
    • 2018-11-05
    • 2020-09-21
    • 2020-04-12
    • 1970-01-01
    • 2022-01-11
    • 2020-04-02
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多