4
votes

Is it possible to deactivate the as.matrix() conversion of apply()?

In the R documentation and in previous posts at stack overflow, I could not find any flags to solve this problem.

Example: Selection of multiple sub matrices from a matrix using apply().

Problem: The apply() function automatically converts the results to a matrix. This leads to one big matrix containing all results.

Code:

#mat contains the data, m the desired column selections 

mat  <- matrix(c(1,2,3,4,
                 2,3,4,1,
                 2,4,3,1,
                 3,4,2,1)
                 ,nrow = 4)

colnames(mat) <- c(1,2,3,4)

m <- matrix(c(1,2,
              3,4)
              ,nrow = 2)   

#Selects first 2 and last 2 columns of mat
#Returns matrix of both results (connected with rbind)
#instead of list of 2 matrices
l <- apply(m,1,function(r)mat[,r])

It is clear that the workaround for this example is simple (select rows manually), but I am trying to write generic code for bigger data sets.

2
Does apply(m, 1, function(r) list(mat[,r])) help? - csgillespie
@csgillespie then you need to get the matrix by l[[n]][[1]] where n is 1 or 2 according to this example. - Tensibai

2 Answers

3
votes

Convert m to a data.frame and then use lapply:

lapply(data.frame(m), function(r) mat[,r])
$X1
     1 2
[1,] 1 2
[2,] 2 3
[3,] 3 4
[4,] 4 1

$X2
     3 4
[1,] 2 3
[2,] 4 4
[3,] 3 2
[4,] 1 1
2
votes

I'm not 100% sure I understand what you're after, but I think this accomplishes it:

target <- list(c(1,2), c(3,4))
l <- lapply(target,function(r)mat[,r])