是否可以停用 apply() 的 as.matrix() 转换?
在 R 文档和之前的堆栈溢出帖子中,我找不到任何标志来解决这个问题。
示例:使用 apply() 从矩阵中选择多个子矩阵。
问题:apply() 函数自动将结果转换为矩阵。这导致一个包含所有结果的大矩阵。
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])
显然,此示例的解决方法很简单(手动选择行),
但我正在尝试为更大的数据集编写通用代码。