【问题标题】:RandomForest in R reports missing values in object, but vector has zero NAs in itR 中的 RandomForest 报告对象中的缺失值,但向量中的 NA 为零
【发布时间】:2016-11-07 15:57:35
【问题描述】:

我正在尝试在 R 中使用 randomForest 包,但我遇到了一个问题,即 R 告诉我响应向量中缺少数据。

> rf_blackcomb_earlyGame <- randomForest(max_cohort ~ ., data=blackcomb_earlyGame[-c(1,2), ])
Error in na.fail.default(list(max_cohort = c(47, 25, 20, 37, 1, 0, 23,  : 
missing values in object

指定的错误很清楚。我以前也遇到过,过去确实有数据丢失,但这次没有任何数据丢失。

> class(blackcomb_earlyGame$max_cohort)
[1] "numeric"
> which(is.na(blackcomb_earlyGame$max_cohort))
integer(0)

我已尝试使用 na.roughfix 来查看是否有帮助,但出现以下错误。

Error in na.roughfix.data.frame(list(max_cohort = c(47, 25, 20, 37, 1,  : 
na.roughfix only works for numeric or factor

我检查了每个向量以确保它们都不包含任何 NA,并且它们都不包含。

有人有什么建议吗?

【问题讨论】:

  • 你能显示sapply(blackcomb_earlyGame, function(x) any(is.na(x)))的输出吗?
  • 我会努力的。我的 R 服务器崩溃了,重新启动它并重新加载数据。
  • 很可能,您有一个字符类型的列。你能发布str(blackcomb_earlyGame)的输出吗?
  • 是的,这似乎是问题所在。有一个专栏,我原以为我会选择一个因素,但它是一个角色。
  • @dww 请将此作为答案发布,以便 OP 可以接受它作为解决方案。另外,请考虑在未来提供一个可重现的示例。

标签: r random-forest


【解决方案1】:

randomForest 可能会因数据存在一些不同类型的问题而失败。缺失值 (NA)、NaNInf-Inf 的值以及未转换为因子的字符类型都会失败,并显示各种错误消息。

我们可以在下面看到每个问题生成的错误消息的一些示例:

my.df <- data.frame(a = 1:26, b=letters, c=(1:26)+rnorm(26))
rf <- randomForest(a ~ ., data=my.df)
# this works without issues, because b=letters is cast into a factor variable by default

my.df$d <- LETTERS    # Now we add a character column
rf <- randomForest(a ~ ., data=my.df)
# Error in randomForest.default(m, y, ...) : 
#   NA/NaN/Inf in foreign function call (arg 1)
# In addition: Warning message:
#   In data.matrix(x) : NAs introduced by coercion

rf <- randomForest(d ~ ., data=my.df)
# Error in y - ymean : non-numeric argument to binary operator
# In addition: Warning message:
#   In mean.default(y) : argument is not numeric or logical: returning NA

my.df$d <- c(NA, rnorm(25))
rf <- randomForest(a ~ ., data=my.df)
rf <- randomForest(d ~ ., data=my.df)
# Error in na.fail.default(list(a = 1:26, b = 1:26, c = c(3.14586293058335,  : 
#   missing values in object

my.df$d <- c(Inf, rnorm(25))
rf <- randomForest(a ~ ., data=my.df)
rf <- randomForest(d ~ ., data=my.df)
# Error in randomForest.default(m, y, ...) : 
#   NA/NaN/Inf in foreign function call (arg 1)

有趣的是,您收到的错误消息是由数据框中的character 类型引起的(请参阅comments),这是我在有一个带有NA 的数字列时看到的错误。这表明(1)来自randomForest 的不同版本的错误可能存在差异,或者(2)错误消息以更复杂的方式取决于数据的结构。无论哪种方式,对于收到此类错误的任何人的建议是查找上面列出的数据的所有可能问题,以便追查原因。

【讨论】:

    【解决方案2】:

    也许有Inf-Inf 值?

    is.na(c(1, NA, Inf, NaN, -Inf))
    #[1] FALSE  TRUE FALSE  TRUE FALSE
    
    is.finite(c(1, NA, Inf, NaN, -Inf))
    #[1]  TRUE FALSE FALSE FALSE FALSE
    

    【讨论】:

      猜你喜欢
      • 2015-11-20
      • 1970-01-01
      • 2020-12-05
      • 2016-11-10
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多