R-套用功能-停用矩阵转换 [英] R - apply function - Deactivation of matrix conversion
问题描述
是否可以停用apply()的as.matrix()转换?
Is it possible to deactivate the as.matrix() conversion of apply()?
在R文档和堆栈溢出的以前的文章中,我找不到任何标志来解决此问题.
In the R documentation and in previous posts at stack overflow, I could not find any flags to solve this problem.
示例:使用apply()从一个矩阵中选择多个子矩阵.
Example: Selection of multiple sub matrices from a matrix using apply().
问题:apply()函数自动将结果转换为矩阵.这导致包含所有结果的一个大矩阵.
Problem: The apply() function automatically converts the results to a matrix. This leads to one big matrix containing all results.
代码:
#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.
推荐答案
将m
转换为data.frame
,然后使用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
这篇关于R-套用功能-停用矩阵转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!