有没有可能在使用apply()函数时取消as.matrix()的转换?
在R文档和之前在stackoverflow上的帖子中,我找不到任何解决此问题的标志。
示例:使用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]))
有帮助吗? - csgillespiel[[n]][[1]]
来获取矩阵,其中 n 根据这个示例为 1 或 2。 - Tensibai