R - 应用功能 - 矩阵转换的停用 [英] R - apply function - Deactivation of matrix conversion

查看:23
本文介绍了R - 应用功能 - 矩阵转换的停用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以停用 apply() 的 as.matrix() 转换?

Is it possible to deactivate the as.matrix() conversion of apply()?

在 R 文档和之前关于堆栈溢出的帖子中,我找不到任何标志来解决这个问题.

In the R documentation and in previous posts at stack overflow, I could not find any flags to solve this problem.

示例:使用 apply() 从矩阵中选择多个子矩阵.

Example: Selection of multiple sub matrices from a matrix using apply().

问题:apply() 函数自动将结果转换为矩阵.这导致包含所有结果的一个大矩阵.

Problem: The apply() function automatically converts the results to a matrix. This leads to one big matrix containing all results.

代码:

#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])

很明显,此示例的解决方法很简单(手动选择行),但我正在尝试为更大的数据集编写通用代码.

It is clear that the workaround for this example is simple (select rows manually), but I am trying to write generic code for bigger data sets.

推荐答案

m 转换为 data.frame 然后使用 lapply:

Convert m to a data.frame and then use 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

这篇关于R - 应用功能 - 矩阵转换的停用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆