简体   繁体   中英

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?

Try the code below

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM