Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort each row of a data frame WITHOUT losing the column names

I’d like to sort each row of a data frame without losing the column names in R.
I know that this accepted answer works, but this method doesn’t keep the names, as shown below:

data_5x3.csv

A,B,C,D,E
5,1,3,2,8
4,3,9,1,6
7,5,2,9,4

My code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

df <- read.csv("data_5x3.csv")

df
#   A B C D E
# 1 5 1 3 2 8
# 2 4 3 9 1 6
# 3 7 5 2 9 4

names(df)
# [1] "A" "B" "C" "D" "E"

sorted_df <- t(apply(df, 1, sort))

sorted_df
#       [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    5    8
# [2,]    1    3    4    6    9
# [3,]    2    4    5    7    9

names(sorted_df)
# NULL

Now the names are gone.
How can we prevent from losing the names?

>Solution :

Store the names and apply them:

nm = names(df)
sorted_df <- as.data.frame(t(apply(df, 1, sort)))
names(sorted_df) = nm

You could compress this down to a single line if you prefer:

sorted_df = setNames(as.data.frame(t(apply(df, 1, sort))), names(df))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading