r - 编写一个 R 函数来检查一个矩阵是否只包含 0 和 1
问题描述
例子
x <- rbind (c(1,0,0), c(0,1,1))
y <- rbind (c(1,2,0), c(0,0,1))
该函数应为 x 返回 true,为 y 返回 false。
要检查是否只有 0 和 1,我尝试使用条件...
all(x==1 || x==0)
all(x==1 && x==0)
但它们似乎不起作用。
解决方案
我们可以使用%in%
with all
。
apply_fun <- function(mat) all(mat %in% c(0, 1))
apply_fun(x)
#[1] TRUE
apply_fun(y)
#[1] FALSE
或使用|
apply_fun <- function(mat) all(mat == 0 | mat == 1)