简体   繁体   中英

R - apply function - Deactivation of matrix conversion

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.

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

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM