在R中对矩阵列进行排序 [英] Sort matrix column in R

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

问题描述

我有一个矩阵(x),其中的几列和几行具有以下形式:

I have a matrix (x) with a few columns and rows of the following form:

2 5 3 6 4
3 6 4 2 5
4 2 5 3 6

我想对列进行排序,使apply(x,2,sort)升序,以后对列中的平均值进行排序.

I want sort columns ascending apply(x,2,sort)and later sort columns ascending the average in column.

输出看起来像这样:

2 2 3 2 3 
3 3 4 5 5
4 6 5 6 6

数据

x <- structure(c(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 6, 6), .Dim = c(3L, 5L))

推荐答案

您可以执行以下操作:

A <- matrix(c(2, 3, 4, 5, 6, 2, 3, 4, 5, 6, 2, 3, 4, 6, 6), ncol=5)
B <- apply(A, 2, sort)
C <- B[, order(apply(B, 2, sum), decreasing = FALSE)]

> C
     [,1] [,2] [,3] [,4] [,5]
[1,]    2    2    3    2    4
[2,]    3    3    4    5    6
[3,]    4    6    5    6    6

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

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