Reputation: 155
I have a large array in r and would like to subset it using points I obtained from a different matrix.
i.e.
,,1
34 1 1 3 4
32 1 3 4 5
23 1 1 3 4
35 1 3 4 4
23 1 2 3 4
,,2
234 1 1 3 4
32 1 3 4 5
324 1 1 3 4
23 1 3 4 4
232 1 2 3 4
and would like it to return
34 1 1 3 4
23 1 1 3 4
23 1 2 3 4
234 1 1 3 4
324 1 1 3 4
232 1 2 3 4
in some format.
These particular rows would be returned as I am choosing based on the last 3 columns (i.e I want all the rows with last 3 digits 1,3,4 and 2,3,4)
Upvotes: 0
Views: 117
Reputation: 887078
One way is
m1 <- apply(ar1, 2, `[`)
m1[m1[,2]%in% 1:2 & m1[,3]==3 & m1[,4]==4,]
# [,1] [,2] [,3] [,4]
#[1,] 1 1 3 4
#[2,] 1 1 3 4
#[3,] 1 2 3 4
#[4,] 1 1 3 4
#[5,] 1 1 3 4
#[6,] 1 2 3 4
Or
res <- do.call(rbind,lapply(seq(dim(ar1)[3]), function(i) {
x1 <- ar1[,,i]
x2 <- t(x1[,-1])
x1[colSums(x2==c(1,3,4)|x2==c(2,3,4))==3,]}))
res
# [,1] [,2] [,3] [,4]
#[1,] 1 1 3 4
#[2,] 1 1 3 4
#[3,] 1 2 3 4
#[4,] 1 1 3 4
#[5,] 1 1 3 4
#[6,] 1 2 3 4
Suppose if the values
to match
are in a matrix
with each row as the matching vector.
toMatch <- rbind(c(1,3,4), c(2,3,4), c(4,3,2), c(1,9,4))
indx1 <- apply(toMatch, 1, paste, collapse="")
res <- do.call(rbind,lapply(seq(dim(ar1)[3]), function(i) {
x1 <- ar1[,,i]
x1[apply(x1[,-1], 1, paste, collapse='') %in% indx1,]
}))
ar1 <- structure(c(1, 1, 1, 1, 1, 1, 3, 1, 3, 2, 3, 4, 3, 4, 3, 4, 5,
4, 4, 4, 1, 1, 1, 1, 1, 1, 3, 1, 3, 2, 3, 4, 3, 4, 3, 4, 5, 4,
4, 4), .Dim = c(5L, 4L, 2L))
Upvotes: 1