5

My data looks like,

A    B    C    D
B    C    A    D
X    Y    M    Z
O    M    L    P

How can I sort the rows to get something like

A    B    C    D
A    B    C    D
M    X    Y    Z
L    M    O    P

Thanks,

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
y2p
  • 4,791
  • 10
  • 40
  • 56

4 Answers4

25
t(apply(DF, 1, sort))

The t() function is necessary because row operations with the apply family of functions returns the results in column-major order.

IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 2
    +1 for compact solution, plus explaining why t() is necessary – Ben Bolker May 19 '11 at 20:14
  • Except the explanation isn't quite right - it's not column major order, it's that new dimensions are added on to the start, not kept in their original positions. – hadley May 19 '11 at 23:20
  • Maybe I am not understanding our difference. `apply()` is building a matrix one column at a time, right? – IRTFM May 20 '11 at 01:47
6

What did you try? This is really straight-forward and easy to solve with a simple loop.

> s <- x
> for(i in 1:NROW(x)) {
+   s[i,] <- sort(s[i,])
+ }
> s
  V1 V2 V3 V4
1  A  B  C  D
2  A  B  C  D
3  M  X  Y  Z
4  L  M  O  P
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
2

No plyr answer yet?!

foo <- matrix(sample(LETTERS,10^2,T),10,10)

library("plyr")

aaply(foo,1,sort)

Exactly the same as DWins answer except that you don't need t()

Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
0

Another fast base R option from Martin Morgan in Fastest way to select i-th highest value from row and assign to new column is

matrix(a[order(row(a), a, method="radix")], ncol=ncol(a))

Timings can be found here

chinsoon12
  • 25,005
  • 4
  • 25
  • 35