如何检查向量中的每个元素在R中是否为整数? [英] How to check if each element in a vector is integer or not in R?
本文介绍了如何检查向量中的每个元素在R中是否为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说,我有一个向量y,我想检查y中的每个元素是否为整数,如果不是,则停止并显示错误消息。我试过is.integer(y),但它不起作用。
Say, I have a vector y, and I want to check if each element in y is integer or not, and if not, stop with an error message. I tried is.integer(y), but it does not work.
推荐答案
最简单(也是最快!)的事情可能是这个:
The simplest (and fastest!) thing is probably this:
stopifnot( all(y == floor(y)) )
...所以试一试:
y <- c(3,4,9)
stopifnot( all(y == floor(y)) ) # OK
y <- c(3,4.01,9)
stopifnot( all(y == floor(y)) ) # ERROR!
如果您想要更好的错误消息:
If you want a better error message:
y <- c(3, 9, NaN)
if (!isTRUE(all(y == floor(y)))) stop("'y' must only contain integer values")
这篇关于如何检查向量中的每个元素在R中是否为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文