R A subset of a logical matrix vector

I would like to multiply a numerical vector with a logical matrix as follows: for vector y

y <- c(4,8,1,3,5,7) 

and the 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 is as follows

 > 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 (), which multiplies y according to the lines of lmat and returns a list. So x (y) will 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 am still studying application functions, and I suspect that this is possible using the application or sapply, despite trying to use one of these functions to get the result I want. I basically want

 y[lmat[1,]] y[lmat[2,]] y[lmat[3,]] 

etc....

but lmat is big, and I think there is a way to do this without a loop. Thanks.

+7
list r apply sapply subset
source share
1 answer
 lapply(1:nrow(lmat), function(i) y[lmat[i,]]) #OR apply(lmat, 1, function(x) y[x]) 
+7
source share

All Articles