r - 检查两个向量是否是子集
问题描述
我正在尝试检查 {1, ..., M} 中是否存在整数 i 使得 a_i = 1 和 b_i = 0 以及 {1,...,M} 中是否存在整数 j 使得 b_j = 1 和a_j = 0。如果成立,则输出 1(无法比较);否则,输出 0(它们是可比较的)。
我试过这个:
a<-c(1,0,1,0)
b<-c(1,0,0,1)
M<-length(a)
incomparable<-function(M, a, b)
{
for(i in 1:M){
for(j in 1:M){
if(a[i]!=b[i] && b[j]!=a[j]) {
print (1)
}
else {
print(0)
}
}
}
}
incomparable(M,a,b)
> incomparable(M,a,b)
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 0
[1] 1
[1] 1
[1] 0
[1] 0
[1] 1
[1] 1
我需要的只是 0 或 1 作为我的输出。如何修复我的代码?
解决方案
我相信这适用于您描述的条件。
incomparable <- function(a,b){
cond1 <- sum(a>b) > 0 # Returns true is if there is at least one case such that a_i is 1 and b_i is 0
cond2 <- sum(b>a) > 0 # True if at least one case such that one case with b_i is 1 and a_i is 0
cond1*cond2
}
##### Check a case where they are incomparable vectors
a<-c(1,0,0,1,0,0,1,0)
b<-c(1,0,0,1,1,0,0,0)
incomparable(a,b)
[1] 1
##### Check case where a = b
a<-c(1,0,0,1)
b<-c(1,0,0,1)
incomparable(a,b)
[1] 0
#### Case where a \subset b
a<-c(1,0,0,0,1,0,1)
b<-c(1,0,0,1,1,0,1)
incomparable(a,b)
[1] 0
### Case where b \subset a
a<-c(1,1,1,0,1,0)
b<-c(1,1,0,0,1,0)
incomparable(a,b)
[1] 0
推荐阅读
- virtual-machine - 无法从 WSL2 Ubuntu ping Ubuntu VM
- android - 保存并恢复后滚动位置只是稍微关闭
- flutter - 从原生控制器返回 Flutter 应用
- primefaces - 如何用空格更改 LineChartSeries 的数字分隔符?
- java - E/MediaPlayer:使用模拟器时出错 (1,-2147483648)
- javascript - Javascript 对象属性值
- r - 在 R 中,如何根据另一个单元格的值删除一系列单元格?
- ios - 固定大小 short[] 数组的动态列表
- delphi - E2001 需要序号类型
- php - 如何让这个 PHP 循环在 Blade 中工作?