Hispalis Guadal
Hispalis Guadal

Reputation: 53

how can i check if all the elements of list are integers in r?

Let's say I have this list:

List_example <- list('short'= 10,'medium'= 20,'long'=200)

How do I check can I check if short, medium and long are integers in one go?

Upvotes: 1

Views: 1716

Answers (3)

G. Grothendieck
G. Grothendieck

Reputation: 269654

If an object has an R integer type then clearly it is a whole number or if it has a double type then we can check if it equals itself rounded.

is_int <- function(x) is.integer(x) || (is.numeric(x) && identical(round(x), x))
all(sapply(List_example, is_int))
## [1] TRUE

L <- list(3, 5L, "xyz")
all(sapply(L, is_int))
## [1] FALSE

If what you mean is that you want to find out if they all have R integer type then we have the following since the numbers in the example are all doubles.

all(sapply(List_example, is.integer))
## [1] FALSE

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101538

Try the code below

> all(sapply(List_example, `%%`, 1) == 0)
[1] TRUE

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

With sapply :

List_example <- list('short'= 10,'medium'= 20,'long'=200)
all(sapply(List_example, is.numeric))
#[1] TRUE

To check for integers specifically use is.integer.

Upvotes: 2

Related Questions