Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting rows alphabetically

Tags:

sorting

r

apply

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,

like image 843
y2p Avatar asked May 19 '11 19:05

y2p


3 Answers

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.

like image 130
IRTFM Avatar answered Oct 16 '22 05:10

IRTFM


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
like image 27
Joshua Ulrich Avatar answered Oct 16 '22 04:10

Joshua Ulrich


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()

like image 2
Sacha Epskamp Avatar answered Oct 16 '22 04:10

Sacha Epskamp