简体   繁体   English

如何检查列表的所有元素是否是 r 中的整数?

[英]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?如何检查是否可以检查一个 go 中的 short、medium 和 long 是否是整数?

Try the code below试试下面的代码

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

With sapply :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 .要检查整数,专门使用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.如果 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

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.如果您的意思是您想知道它们是否都具有 R integer 类型,那么我们有以下内容,因为示例中的数字都是双精度数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查列表的所有元素在 R 中是否相等 - check whether all elements of a list are in equal in R 如何将 1 添加到包含整数和 NA(在 R 中)的数据集中的所有整数? - How can I add 1 to all integers in a dataset consiting integers and NAs (in R)? 如何检查嵌套列表的所有元素是否是 R 中另一个列表的子集 - How to check whether all elements of a nested list are a subset of another list in R 如何检查向量的所有元素是否都在列表中,添加一列,其中包含发生这种情况的列表名称(在 R 中) - How to check if all elements of a vector are in a list, adding a column with the name of the list where this occurs (in R) 如何检查R中列表元素的存在 - How to check the existence of elements of list in r 如何在R中的单个字符串中打印矢量的所有元素? - How can I print all the elements of a vector in a single string in R? 如何在R中访问字符串列表的元素? - How can I access the elements of a string list in R? 如何访问R中列表元素的组件 - How can I access components of list elements in R 如何通过提取包含字符串的元素来对 r 中的列表进行子集化? - How can I subset a list in r by extracting the elements that contain a string? r - 检查列表的所有元素是否与向量完全匹配 - r - check is all elements of a list match a vector exactly
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM