[英]how can i check if all the elements of list are integers in r?
假設我有這個列表:
List_example <- list('short'= 10,'medium'= 20,'long'=200)
如何檢查是否可以檢查一個 go 中的 short、medium 和 long 是否是整數?
試試下面的代碼
> all(sapply(List_example, `%%`, 1) == 0)
[1] TRUE
用sapply
:
List_example <- list('short'= 10,'medium'= 20,'long'=200)
all(sapply(List_example, is.numeric))
#[1] TRUE
要檢查整數,專門使用is.integer
。
如果 object 有一個 R integer 類型,那么很明顯它是一個整數,或者如果它有一個 double 類型,那么我們可以檢查它是否等於自己四舍五入。
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
如果您的意思是您想知道它們是否都具有 R integer 類型,那么我們有以下內容,因為示例中的數字都是雙精度數。
all(sapply(List_example, is.integer))
## [1] FALSE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.