8

I am trying to sort each row of a data frame using this line,

sapply(df, function(x) sort(x))

However, the columns are getting sorted instead of the rows.

For example, this data frame

5          10          7          1          5
6           3          9          2          4
4           5          1          3          3

is ending up like this:

4           3          1          1          3
5           5          7          2          4
6          10          9          3          5

And I want this:

1 5 5 7 10
2 3 4 6 9
1 3 3 4 5

Any recommendations? Thanks

Henrik
  • 65,555
  • 14
  • 143
  • 159
user3276768
  • 1,416
  • 3
  • 18
  • 28

2 Answers2

19

You could use the plain apply function with MARGIN = 1 to apply over rows and then transpose the result.

t(apply(df, 1, sort))
cdeterman
  • 19,630
  • 7
  • 76
  • 100
  • If MARGIN was 2, the output would have been the Matrix, but sorted by the columns. Why do we have to transpose it while sorting according to Rows? – Varun Gawande Aug 26 '21 at 11:24
5

You can transpose it (coverts it to matrix), and split by column and sort

t(sapply(split(t(df), col(t(df))), sort))
#   [,1] [,2] [,3] [,4] [,5]
# 1    1    5    5    7   10
# 2    2    3    4    6    9
# 3    1    3    3    4    5

Because a data.frame is a list of columns, when you sapply like that you are sorting the columns.

or apply by row

t(apply(df, 1, sort))
Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • I had a similar idea: `do.call(rbind, lapply(split(df, seq_len(nrow(df))), sort))` I think any approach here involves converting each row to an atomic vector (so it can be sorted), which is roughly the same as converting the whole thing to matrix. – Frank Jul 31 '15 at 18:16
  • @Frank yea that works too, very slow for larger data though – Rorschach Jul 31 '15 at 18:29
  • Hm, maybe so -- that `t(sapply(` beats `do.call(rbind,lapply(` -- though it's not obvious to me why. For the other part, transposing before splitting looks wasteful and inferior to `split(df,seq_len(nrow(df)))`. If you have some benchmark in favor of transposing, I'd be surprised and interested. – Frank Jul 31 '15 at 18:55
  • 1
    @Frank yes, the first part is the slow part – Rorschach Jul 31 '15 at 19:02