I have two matrix:
A <- structure(c(0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1,
0, 0, 1), .Dim = c(10L, 2L), .Dimnames = list(NULL, c("a", "b"
)))
B <- structure(c(1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0), .Dim = c(10L, 2L), .Dimnames = list(NULL, c("c", "d"
)))
and I fund the number of the rows in A that contain the first "1":
a_1 <- t(as.matrix(max.col(t(A) == 1, "first")))
and it return "4 , 3". Now I need to know the number of the rows in B that contain the first "1", after the rows I got as output from A ("4" and "2" respectively). The result I expect is "5" for the first col of B and "NA" (or something like that) for the second. How can I do? Thx for help!
CodePudding user response:
Here is an approach:
sapply(seq_along(a_1), \(i) {
k =which(B[,i]==1);k[which(k>a_1[i])][1]
})
Output:
[1] 5 NA
CodePudding user response:
Perhaps this helps
apply((row(B) >c(a_1)[col(B)]) * B, 2, \(x) which(x==1)[1])
c d
5 NA