Thursday, July 10, 2014

sort data in each row in R data set

Suppose we have this kind of data A
And want to sort from the maximum until the minimum value each row

> A
    [1]      [2]          [3]          [4]
[1] 3       7             9              5
[2] 7       9            11             3
[3] 5       3            7               8

We want to sort A by row and resulting like this
    [1]      [2]          [3]          [4]
[1] 3       5             7             9
[2] 3       7             9            11
Etc....

We can sort by row by doing this
>Asorted = t(apply(A,1,sort))  
#sort the data A each row and input to Asorted data

apply(A,1,sort) means apply for A data set, in 1 (row), and sort them
*1: row, 2: column and (1:2): both of row and column

Yet it will be like this. It will be sorted from the minimum value to the maximum value in each row  (reverse)

    [1]      [2]          [3]          [4]
[1] 3       5             7             9
[2] 3       7             9            11
Etc....

What we need to do next is just reverse it by this command
>Asorted = Asorted[ ,ncol(Asorted):1]    
#reverse sequence in column index, and input it (rewrite) to Asorted data

There you go, the result would be like this
>Asorted

    [1]      [2]          [3]          [4]
[1] 9       7             5            3
[2] 11     9             7            3
Etc....

No comments:

Post a Comment