【问题标题】:Avoiding NAs in as.numeric()在 as.numeric() 中避免 NA
【发布时间】:2012-10-23 01:10:32
【问题描述】:

如果我这样做,我会得到正确的结果:

a <- c("10","28","3")
which(as.numeric(a) == min(as.numeric(a)))
[1] 3

但是如果向量中有NA,那就有问题了

a <- c("10","28","3","NA")
which(as.numeric(a) == min(as.numeric(a)))
integer(0)
Warning messages:
1: In which(as.numeric(a) == min(as.numeric(a))) :
  NAs introduced by coercion
2: In which(as.numeric(a) == min(as.numeric(a))) :
  NAs introduced by coercion

【问题讨论】:

  • 标题中不需要 R,因为您已将其标记为 r

标签: r na


【解决方案1】:

两件事。

首先,字符串"NA" 和缺失值的R 数据表示NA 之间存在差异。删除示例中 NA 周围的引号以查看:

a <- c("10","28","3",NA)

其次,当您使用 min实际 缺失值(即不是字符串 "NA")时,您将希望使用 na.rm = TRUE

which(as.numeric(a) == min(as.numeric(a),na.rm = TRUE))

【讨论】:

  • 您指出“NA”是对的。这是一个错字。它旨在成为缺失值的 NA。感谢您的解决方案。
  • 您可能还想使用which.min
【解决方案2】:

您的主要问题是没有在对 min 的调用中指定 na.rm = TRUE

numeric_a <- as.numeric(a)

which(numeric_a == min(numeric_a, na.rm = TRUE))
## [1] 3

或者您可以使用which.min,它不需要您指定应该删除 NA 值。这只会给你第一场比赛,而不是所有比赛(感谢@Dason提醒我澄清这一点)

which.min(numeric_a)

【讨论】:

  • 但是如果您使用which.min,请注意即使有多个值与最小值匹配,您也只会得到一个结果。
  • mnel 和 Dason,感谢你们两位对解决方案的进一步说明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多