R - apply function - Deactivation of matrix conversion -
is possible deactivate as.matrix() conversion of apply()?
in r documentation , in previous posts @ stack overflow, not find flags solve problem.
example: selection of multiple sub matrices matrix using apply().
problem: apply() function automatically converts results matrix. leads 1 big matrix containing results.
code:
#mat contains data, m 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 , last 2 columns of mat #returns matrix of both results (connected rbind) #instead of list of 2 matrices l <- apply(m,1,function(r)mat[,r])
it clear workaround example simple (select rows manually), trying write generic code bigger data sets.
convert m
data.frame
, 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
Comments
Post a Comment