【问题标题】:R - apply function - Deactivation of matrix conversionR - 应用功能 - 矩阵转换的停用
【发布时间】: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。

标签: r matrix apply


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我不是 100% 确定我了解您的需求,但我认为这可以实现:

    target <- list(c(1,2), c(3,4))
    l <- lapply(target,function(r)mat[,r])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-19
      • 2019-10-16
      • 2018-01-09
      • 2013-06-26
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多