Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

integer

r

vector

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.

like image 615
zca0 Avatar asked Apr 11 '12 21:04

zca0


People also ask

How do I check if a variable is an integer in R?

To check if type of given vector is integer in R, call is. integer() function and pass the vector as argument to this function. If the given vector is of type integer, then is. integer() returns TRUE, or else, it returns FALSE.

How do you check if value is in a vector in R?

%in% operator can be used in R Programming Language, to check for the presence of an element inside a vector. It returns a boolean output, evaluating to TRUE if the element is present, else returns false.

How do I find the type of a vector in R?

A vector's type can be checked with the typeof() function. Another important property of a vector is its length. This is the number of elements in the vector and can be checked with the function length() .

How do I check if a value is a number in R?

Check if an Object is of Type Numeric in R Programming – is. numeric() Function. is. numeric() function in R Language is used to check if the object passed to it as argument is of numeric type.


4 Answers

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")
like image 58
Tommy Avatar answered Oct 18 '22 02:10

Tommy


you could do:

   y <- c(3,3.1,1,2.3)
   (y - floor(y)) == 0
    [1]  TRUE FALSE  TRUE FALSE

or

   (y - round(y)) == 0

and if you want a single TRUE or FALSE for the whole thing, put it in all(), e.g.:

   all((y - round(y)) == 0)
    [1] FALSE
like image 30
tim riffe Avatar answered Oct 18 '22 04:10

tim riffe


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
like image 7
Michael Dunn Avatar answered Oct 18 '22 04:10

Michael Dunn


Not sure which is faster Tim's way or this, but:

> x <- 1:5
> y <- c(x, 2.0)
> z <- c(y, 4.5)
> all.equal(x, as.integer(x))
[1] TRUE
> all.equal(y, as.integer(y))
[1] TRUE
> all.equal(z, as.integer(z))
[1] "Mean relative difference: 0.1111111"
> 

or:

all((z - as.integer(z))==0)
like image 4
Justin Avatar answered Oct 18 '22 02:10

Justin