How can I use the row.names attribute to order the rows of my dataframe in R?

This worked for me:

new_df <- df[ order(row.names(df)), ]

For completeness:

@BondedDust's answer works perfectly for the rownames attribute, but your example does not use the rownames attribute. The output provided in your question indicates use of a column named "row.names", which isn't the same thing (all listed in @BondedDust's comment). Here would be the answer if you wished to sort by the "row.names" column in example given in your question (there is another posting on this, located here). This answer assumes you are using a dataframe named "df", with one column named "row.names":

ordered.df <- df[order(df$row.names),]   #this orders the df by the "row.names" column

Alternatively, to order by the first column (same thing if you're still using your example):

ordered.df <- df[order(df[,1]),]         #this orders the df by the first column

Hope this is helpful!


None of the other solutions would actually work.

It should be:

# Assuming the data frame is called df
df[ order(as.numeric(row.names(df))), ]

because the row name in R is character, when the as.numeric part is missing it, it will arrange the data as 1, 10, 11, ... and so on.


If you have only one column in your dataframe like in my case you have to add drop=F:

df[ order(rownames(df)) , ,drop=F]