I would like to subset a numeric vector with a logical matrix in the following way: Given a vector y
y <- c(4,8,1,3,5,7)
and a logical matrix lmat
lmat <- t(matrix(c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
TRUE, FALSE, FALSE, FALSE, FALSE, FALSE,
FALSE, TRUE, FALSE, FALSE, FALSE, FALSE,
TRUE, TRUE, FALSE, FALSE, FALSE, FALSE,
FALSE, FALSE, TRUE, FALSE, FALSE, FALSE,
TRUE, FALSE, TRUE, FALSE, FALSE, FALSE), ncol = 6))
which looks like this
> lmat
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] FALSE FALSE FALSE FALSE FALSE FALSE
[2,] TRUE FALSE FALSE FALSE FALSE FALSE
[3,] FALSE TRUE FALSE FALSE FALSE FALSE
[4,] TRUE TRUE FALSE FALSE FALSE FALSE
[5,] FALSE FALSE TRUE FALSE FALSE FALSE
[6,] TRUE FALSE TRUE FALSE FALSE FALSE
I want to apply some function x() that subsets y according to the rows of lmat and returns a list. So x(y) would return:
[[1]]
numeric(0)
[[2]]
[1] 4 9
[[3]]
[1] 8
[[4]]
[1] 4 8 9
[[5]]
[1] 1
[[6]]
[1] 4 1 9
I'm still learning the apply functions and I suspect this is somehow possible with apply or sapply despite trying to use one of those functions to get the result I want. I basically want
y[lmat[1,]]
y[lmat[2,]]
y[lmat[3,]]
etc....
but lmat is large and I think there is a way to do with without a loop. Thanks.
lapply(1:nrow(lmat), function(i) y[lmat[i,]])
#OR
apply(lmat, 1, function(x) y[x])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With