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

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

    I went in a completely different direction then Tim (I like his better though my approach works on a mixed vector that's a character vector with integers etc.):

    int.check <- function(vect) {
        vect <- as.character(vect)
        sapply(vect, function(x) all(unlist(strsplit(x, ""))%in% 0:9))
    }
    
    x <- c(2.0, 1111,"x", 2.4)
    int.check(x)
    

    EDIT: altered the function as it only worked on character vectors.

    This works on vectors of the class character as well in case you have a character vector with various number intermixed but that have been coerced to character.

    0 讨论(0)
提交回复
热议问题