【发布时间】:2015-11-18 21:32:43
【问题描述】:
是否可以停用 apply() 的 as.matrix() 转换?
在 R 文档和以前的堆栈溢出帖子中,我找不到任何标志来解决这个问题。
示例:使用 apply() 从矩阵中选择多个子矩阵。
问题:apply() 函数自动将结果转换为矩阵。这导致一个包含所有结果的大矩阵。
代码:
#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])
很明显,此示例的解决方法很简单(手动选择行), 但我正在尝试为更大的数据集编写通用代码。
【问题讨论】:
-
apply(m, 1, function(r) list(mat[,r]))有帮助吗? -
@csgillespie 然后您需要通过
l[[n]][[1]]获取矩阵,根据此示例,其中 n 为 1 或 2。