Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting each row of a data frame [duplicate]

Tags:

sorting

r

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

like image 359
user3276768 Avatar asked Jul 31 '15 18:07

user3276768


People also ask

How do I remove duplicate rows in a data frame?

You can set 'keep=False' in the drop_duplicates() function to remove all the duplicate rows. For E.x, df. drop_duplicates(keep=False) .

How do I find duplicate rows in a DataFrame in R?

We can find the rows with duplicated values in a particular column of an R data frame by using duplicated function inside the subset function. This will return only the duplicate rows based on the column we choose that means the first unique value will not be in the output.


1 Answers

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

t(apply(df, 1, sort))
like image 166
cdeterman Avatar answered Oct 11 '22 12:10

cdeterman