Reputation: 69
comN<-gtools::permutations(2,5,v=c(0,1),repeats=TRUE)
which(comN==c(0,0,0,0,1),arr.ind.col=T)
but it didn't give me the row number 2
I want to know c( 0,0,0,0,1) is on position comN [2,]
Upvotes: 2
Views: 32
Reputation: 388907
We can use sweep
to compare row-wise values of comN
with the vector and use rowSums
to count number of TRUE
in each row
which(rowSums(sweep(comN, 2, c(0,0,0,0,1), `==`)) == ncol(comN))
#[1] 2
Instead of rowSums
, we can also use apply
since sweep
already returns a matrix of logical vectors
which(apply(sweep(comN, 2,c(0,0,0,0,1), `==`), 1, all))
Upvotes: 0
Reputation: 76402
R's matrix operations are in column order, so the comparison in your which
instruction compares the vector c(0,0,0,0,1)
column by column, recycling it. Just see what happens in this simple example.
m <- matrix(1:8, ncol = 2)
m
# [,1] [,2]
#[1,] 1 5
#[2,] 2 6
#[3,] 3 7
#[4,] 4 8
m == c(1, 5)
# [,1] [,2]
#[1,] TRUE FALSE
#[2,] FALSE FALSE
#[3,] FALSE FALSE
#[4,] FALSE FALSE
The vector c(1, 5)
is not compared with the first row, the comparisons are
c(1, 2) == c(1, 5)
then c(1, 5)
is recycled and compared with the next values in the first column. So when it reaches the second column the first comparison in that column is
c(5, 6) == c(1, 5)
#[1] FALSE FALSE
returning c(FALSE, FALSE)
.
This is why I needed the transpose t()
in my solutions below.
A way could be
which(colSums(t(comN) == c(0,0,0,0,1)) == ncol(comN))
#[1] 2
or
which(apply(t(comN) == c(0,0,0,0,1), 2, all))
The colSums
solution is around 3 times faster.
Upvotes: 1