How to check if each element in a vector is integer or not in R?

前端 未结 7 874
感动是毒
感动是毒 2021-01-11 14:52

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.

7条回答
  •  粉色の甜心
    2021-01-11 15:17

    If you have floating-point representation error, try:

    round( y, TOLERANCE.DIGITS ) %% 1 == 0
    

    In my application, I had seriously brutal floating-point representation error, such that:

    > dictionary$beta[3]
    [1] 89
    > floor(dictionary$beta[3])
    [1] 88
    > as.integer( dictionary$beta )[3]
    [1] 88
    > dictionary$beta[3] %% 1
    [1] 1
    

    the remainder divided by one was one. I found that I had to round before I took the integer. I think all of these tests would fail in the case where you wanted the above 89 to count as an integer. The "all.equal" function is meant to be the best way to handle floating-point representation error, but:

    all.equal( 88, 89 );
    

    as in my case, would have (and did) given a false negative for an integer value check.

    EDIT: In benchmarking, I found that:

    (x == as.integer(x)) 
    

    was universally the best performer.

    (x == floor(x))
    ((x - as.integer(x)) == 0)
    

    usually worked well, often just as fast.

    (x %% 1 <= tolerance)
    

    works, but not as quickly as the others

    !(is.character(all.equal(x, as.integer(x)))) 
    

    when the vector wasn't integers, had terrible performance (certainly because it goes to the trouble of estimating the difference).

    identical(x, as.integer(x)) 
    

    when the vector was all integer values, returned the incorrect result (assuming the question was meant to check for integer values, not integer types).

提交回复
热议问题