【问题标题】:why do i get NAs introduced by coercion warning message?为什么我会收到强制警告消息引入的 NA?
【发布时间】:2017-06-20 23:12:18
【问题描述】:

我正在使用以下方法将“是”、“否”响应转换为数字数据,以便我可以将结果绘制成散点图。

> head(cust.df$email)
[1] "yes" "yes" "yes" "yes" "no"  "yes"

> as.numeric(head(cust.df$email))
[1] NA NA NA NA NA NA
Warning message:
NAs introduced by coercion 

如您所见,我收到此警告消息。最终结果是,当我创建散点图时,由于 NA,它是空的。

我什至尝试过用这种方法修复它。

as.factor(head(cust.df$email))
yes yes yes yes no  yes
Levels: no yes

> as.numeric(head(cust.df$email))
[1] NA NA NA NA NA NA
Warning message:
NAs introduced by coercion

但是,这些都没有奏效。有人对如何解决这个问题有任何提示吗?数据确实有 341 个 NA。

【问题讨论】:

  • 如果您提供reproducible example 会更容易提供帮助。 class(cust.df$email) 是什么?另外,你想要什么值是/否? 0/1? 1/0? 2/10?
  • 感谢弗利克先生,
  • 这是一个字符。我想要 2=是,1=否
  • 您的修复不起作用,因为您转换为因子,但您没有将新的因子值分配给变量。你需要做类似cust.df$email <- as.numeric(as.factor(cust.df$email))的事情。
  • 我明白你的意思。我按照你的指示,现在它的作品。非常感谢。

标签: r


【解决方案1】:

据我所知,yes 和 no 不等于 R 中的 0 和 1。但是,它适用于 TRUE 和 FALSE。您需要直接为“yes”和“no”赋值。

cust.df$email<-factor(cust.df$email)
cust.df$email<-as.numeric(cust.df$email)

这将为您的数据分配 1 和 2,如果您想要 0 和 1,那么您可以简单地使用:

cust.df$email[cust.df$email==2]&lt;-0

【讨论】:

    【解决方案2】:

    一种可能的处理方法是在散点图中使用as.numeric(as.factor(email))。这是一个展示其工作原理的示例:

    stuff <- sample(c("yes","no",NA), 10, replace=T)
    stuff
    #   [1] "yes" "no"  "yes" NA    NA    "no"  "no"  "yes" "yes" "no" 
    
    as.numeric(as.factor(stuff))
    #   [1]  2  1  2 NA NA  1  1  2  2  1
    

    as.numeric(head(cust.df$email)) 不起作用的原因是因为您只显示了head(cust.df$email)factor 表示,您没有将cust.df$email 转换为因子。

    另一种可能的方法是创建一个新变量 - 这将是一种使用您想要的任何数字代码的简单方法:

    stuff_num <- rep(NA, length(stuff))
    stuff_num[stuff=="yes"] <- 2
    stuff_num[stuff=="no"] <- 1
    stuff_num
    #   [1]  2  1  2 NA NA  1  1  2  2  1
    

    【讨论】:

    • 是的,感谢您帮助我看到这一点。作为 R 的新手,我很欣赏您的替代解决方案。 R 很有趣,而且学习曲线也不错。
    【解决方案3】:

    我之前遇到过这个问题,问题出在我从中读取的 .csv 文件上。对我来说,细胞有“,”这样的问题 1,

    当我删除它时,它就像一个魅力。希望这可以帮助将来遇到此问题的任何人。

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多