Frederique vdb Frederique vdb - 1 month ago 27
R Question

Change row names in R, sort by date

I have a dataframe of which the first column is a date object (used lubridate) and the other columns show number of items sold. I'm having issues with the row names (numbers). That is, the row names are not in order of the dates:

enter image description here

I tried using rownames, but I can't figure out how to sort the row names by date, so that july 28 becomes '2', july 29 becomes '3', etc.
Does anybody have a way to achieve this?
If additional information is needed, please let me know.
Thanks in advance!

Answer Source

You can use the built-in order function:

newdata <- df[order(df$Date),]

If rownames persist out of order, you can reset them:

rownames(newdata) <- NULL