R - 应用功能 - 停用矩阵转换
R - apply function - Deactivation of matrix conversion
是否可以停用 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])
很明显,此示例的解决方法很简单(手动 select 行),
但我正在尝试为更大的数据集编写通用代码。
我不是 100% 确定我了解您的需求,但我认为这可以实现:
target <- list(c(1,2), c(3,4))
l <- lapply(target,function(r)mat[,r])
将 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
是否可以停用 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])
很明显,此示例的解决方法很简单(手动 select 行), 但我正在尝试为更大的数据集编写通用代码。
我不是 100% 确定我了解您的需求,但我认为这可以实现:
target <- list(c(1,2), c(3,4))
l <- lapply(target,function(r)mat[,r])
将 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