如果我这样做,我会得到正确的结果:
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
答案 0 :(得分:13)
两件事。
首先,字符串"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))
答案 1 :(得分:8)
您的主要问题是未在na.rm = TRUE
min
numeric_a <- as.numeric(a)
which(numeric_a == min(numeric_a, na.rm = TRUE))
## [1] 3
或者您可以使用不需要您指定应删除NA值的which.min
。这只会给你第一场比赛,而不是所有比赛(感谢@Dason提醒我澄清这一点)
which.min(numeric_a)