我有一个矩阵:
a<-replicate(3,sample(c(0,1),4, replace=T))
和矢量:
b<-c(0,1,0)
我想在a
中找出与向量b
对应的行号。
查看a==b
我可以看到每个条件返回TRUE
的行,但是如何获取行号?
答案 0 :(得分:2)
set.seed(42)
a < -replicate(3, sample(c(0, 1), 4, replace=T))
# [,1] [,2] [,3]
#[1,] 1 1 1
#[2,] 1 1 1
#[3,] 0 1 0
#[4,] 1 0 1
b <- c(0, 1, 0)
#vector recycling is done in row direction --> transpose the matrix
#logical values get coerced to integers in colSums
which(colSums(t(a) == b) == 3L)
#[1] 3
答案 1 :(得分:1)
set.seed(1)
a <- replicate(3,sample(c(0,1),4, replace=T))
b<-c(0,1,0)
which(apply(a, 1, FUN=function(x) all(x == b)))
# [1] 2
答案 2 :(得分:0)
set.seed(15)
a <- replicate(5,sample(c(0,3),6, replace=T))
b<-c(0,1,0)
which(apply(a, 1, FUN=function(x) all(x == b)))