Hi:
The problem is that in your example, you have unequal numbers of rows
in B that match the 1's pattern in A[i, ]. The function below cycles
through the rows of A and returns, for each row of A, the rows in B
that have 1's in the same columns as A[i, ]. By necessity, this
returns a list. Notice that in the last row of A, no rows of B match
its 1's pattern.
f <- function(i) {
idx <- which(A[i, ] == 1L)
g <- function(x) all(x[idx] == 1)
which(apply(B, 1, g))
}
lapply(seq_len(nrow(A)), f)
[[1]]
[1] 6
[[2]]
[1] 4 6 8 10
[[3]]
[1] 10
[[4]]
[1] 11 12 14
[[5]]
integer(0)
If you want the corresponding rows of B in each list component, then a
simple modification of the function will provide that:
f2 <- function(i) {
idx <- which(A[i, ] == 1L)
g <- function(x) all(x[idx] == 1)
B[which(apply(B, 1, g)), , drop = FALSE]
}
lapply(seq_len(nrow(A)), f2)
[[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 0
[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 0 1 1 0
[2,] 1 1 1 1 0
[3,] 1 0 1 0 1
[4,] 1 1 1 0 1
[[3]]
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 0 1
[[4]]
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 1 1 1
[2,] 0 1 1 1 1
[3,] 1 0 0 1 1
[[5]]
[,1] [,2] [,3] [,4] [,5]
HTH,
Dennis
On Mon, Sep 26, 2011 at 4:03 PM, Thiem Alrik <thiem at sipo.gess.ethz.ch>
wrote:> Dear mailing list,
>
> how can I identify all those rows of matrix B which fulfill some condition
based on another matrix A? More precisely,
>
> A <- matrix(c(1, 1, 0, 1, -9, 1, -9, 1, 0, 0, 1, 1, 0, -9, 1, 0, -9, 0,
1, 1, 1, -9, 1, 1, 1), ncol = 5, byrow = TRUE)
>
> B <-
matrix(c(0,0,1,0,0,0,1,1,0,0,0,0,1,1,0,1,0,1,1,0,0,1,1,1,0,1,1,1,1,0,0,0,1,0,1,1,
>
0,1,0,1,0,1,1,0,1,1,1,1,0,1,0,0,1,1,1,0,1,1,1,1,1,0,0,1,0,1,0,0,1,1,0,1,0,0,1),
ncol = 5, byrow = TRUE)
>
> Row 1 in A has value 1 on element 1, 2 and 4. Which rows in B also display
this pattern? Only row 6.
> Row 2 in A has value 1 on element 1 and 3. Which rows in B also display
this pattern? Rows 4, 6, 8 and 10.
> ...
> Row 5 in A ...
>
> C <- rbind(4, 6, 8, 10, ...)
>
> How can I collect together all those rows from B to create a new matrix C?
>
> Thanks a lot,
>
> Alrik
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>