R:仅按列的一部分进行矩阵排序

时间:2016-05-08 17:01:54

标签: r sorting matrix

我有一个矩阵,说:

'use strict';  
 var app = angular.module('myApp', []);

 app.controller('MyController', function($scope, $http){
   $http.get('sample.json').then(function (response){
    $scope.items = response.data.countries;
   });
 });

所以:

<body ng-app="myApp">
    <div ng-controller="MyController">
        <ul>
            <li ng-repeat="(key, value) in items" {{key}}>

            </li>
        </ul>
    </div>
</body>

我知道如何按列[,3]的绝对值对M进行排序(例如):

c <- c(1,2,3,4,5,0,1,-5,3,1,-3,2,-2,1,2,0,1,0,3,3,5,-5,3,-1,0)
M <- matrix(c, byrow=T, nrow=5)
M 

所以:

M
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    0    1   -5    3    1
[3,]   -3    2   -2    1    2
[4,]    0    1    0    3    3
[5,]    5   -5    3   -1    0

但我想要的是M不是按整列[3]排序,而是仅按最后3个绝对值排序,这样M的前两行不会改变:

Ma <- abs(M)
Ms <- M[order(Ma[,3], decreasing = T),]
Ms 

我无法以简单的方式找到如何做到这一点。有什么想法?
感谢。

2 个答案:

答案 0 :(得分:2)

我们可以尝试

M[(nrow(M)-2):nrow(M),] <- tail(M,3)[order(tail(Ma[,3],3), decreasing=TRUE),]
M
#      [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]    0    1   -5    3    1
#[3,]    5   -5    3   -1    0
#[4,]   -3    2   -2    1    2
#[5,]    0    1    0    3    3

答案 1 :(得分:0)

M[c(1:2,2L+order(abs(M[-1:-2,3L]),decreasing=T)),];
##      [,1] [,2] [,3] [,4] [,5]
## [1,]    1    2    3    4    5
## [2,]    0    1   -5    3    1
## [3,]    5   -5    3   -1    0
## [4,]   -3    2   -2    1    2
## [5,]    0    1    0    3    3
相关问题