检查数字是否为整数 [英] Check if the number is integer
问题描述
我很惊讶地发现R没有方便的功能来检查数字是否为整数。
I was surprised to learn that R doesn't come with a handy function to check if the number is integer.
is.integer(66) # FALSE
is.integer(x)
不测试x
是否包含整数!为此,
使用round
,如函数
is.wholenumber(x)
在示例中。
is.integer(x)
does not test ifx
contains integer numbers! For that, useround
, as in the functionis.wholenumber(x)
in the examples.
该示例将此自定义函数作为解决方法
The example has this custom function as a "workaround"
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol
is.wholenumber(1) # is TRUE
如果我要写一个检查整数的函数,假设我没有读过上面的注释,我会编写一个函数,它会像
If I would have to write a function to check for integers, assuming I hadn't read the above comments, I would write a function that would go something along the lines of
check.integer <- function(x) {
x == round(x)
}
我的方法在哪里失败?如果你穿着我的假想鞋,你的工作会是什么?
Where would my approach fail? What would be your work around if you were in my hypothetical shoes?
推荐答案
另一个选择是检查小数部分:
Another alternative is to check the fractional part:
x%%1==0,
或,
min(abs(c(x%%1, x%%1-1))) < tol,
如果你想在一定的公差范围内检查。
if you want to check within a certain tolerance.
这篇关于检查数字是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!