根据另一个矩阵对一个矩阵进行排序 [英] Sort one matrix based on another matrix

查看:166
本文介绍了根据另一个矩阵对一个矩阵进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个矩阵的行与相同维度的另一个矩阵的行置于相同的顺序.但是我不知道如何在没有显式循环的情况下执行此操作.看来我应该可以使用子集和Apply或Map函数来做到这一点,但是我不知道该怎么做.

I'm trying to put the rows of one matrix in the same order as the rows of another matrix of the same dimension. However I can't quite figure out how to do this without an explicit loop. It seems I should be able to do this with subsetting and an apply or Map function, but I can't figure out how to do it.

这是一个玩具示例:

sortMe <- matrix(rnorm(6), ncol=2)
sortBy <- matrix(c(2,1,3, 1,3,2), ncol=2)

sorted <- sortMe 
for (i in 1:ncol(sortMe)) {
  sorted[,i] <- sortMe[,i][sortBy[,i]]
}

使用此方法,所得的sorted矩阵包含以与sortBy矩阵相同的顺序排序的sortMe中的值.知道我如何在没有循环的情况下做到这一点吗?

Using this method, the resulting sorted matrix contains the values from sortMe sorted in the same order as the sortBy matrix. Any idea how I'd do this without the loop?

推荐答案

此方法(使用两列整数矩阵索引矩阵的二维)应该可以解决问题:

This (using a two-column integer matrix to index the matrix's two dimensions) should do the trick:

sorted <- sortMe
sorted[] <- sortMe[cbind(as.vector(sortBy), as.vector(col(sortBy)))]

这篇关于根据另一个矩阵对一个矩阵进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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