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

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

    The simplest (and fastest!) thing is probably this:

    stopifnot( all(y == floor(y)) )
    

    ...So trying it out:

    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")
    

提交回复
热议问题