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

前端 未结 7 862
感动是毒
感动是毒 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:18

    Here's another way (using the same trick as Justin of comparing each number to that number coerced into the 'integer' type):

    R> v1 = c(1,2,3)
    R> v2 = c(1,2,3.5)
    R> sapply(v1, function(i) i == as.integer(i))
    [1] TRUE TRUE TRUE
    R> sapply(v2, function(i) i == as.integer(i))
    [1]  TRUE  TRUE FALSE
    

    To make your test:

    R> all(sapply(v2, function(i) i == as.integer(i)))
    [1] FALSE
    

提交回复
热议问题