Given the following vector of length n=10
:
# [1] 0 0 0 0 0 1 0 0 1 0
vec <- c(0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 1L, 0L)
Suppose we want to apply the operator &
to all possible combinations of the vector elements. That is:
res <- combn(n, 2, function(v) vec[v[1]]&vec[v[2]])
# total number of possible combinations is n(n-1)/2 = 45
However, we know that the result of &
operator is true only when both values are 1
and hence, we can do it in a more clever way. In fact, the result of combn
is a vector of length 45
with only one value of 1
and the rest are just 0
.
Now the question is that how we can extract the position of the only 1
without applying the combn
itself? Once we can get it, we generate the result simply as follow:
res <- rep(0, 45)
res[index] <- 1
where index
is the questioned position.