How to order dates in R?

Viewed 334

I have a dataframe

         date               dz1       hs1     tm1      ft1     pv1
 2021-03-21 18:12:37         30       15       0        5       25
 2021-03-21 12:10:13         39       25      15       15       20
 2021-03-24 18:06:33         30       30       0       39       40
 2021-03-24 21:02:22         30       20       0       25       40
 2021-03-21 15:11:06         25       15      19       20       20
 2021-03-20 18:03:06         34       20      21        0       30

I am trying to sort the data by date. Essentially, I need the date column to be sorted in increasing date.

Like this

   date                      dz1       hs1     tm1      ft1     pv1
 2021-03-20 18:03:06         34       20      21        0       30
 2021-03-21 12:10:13         39       25      15       15       20
 2021-03-21 15:11:06         25       15      19       20       20
 2021-03-21 18:12:37         30       15       0        5       25
 2021-03-24 18:06:33         30       30       0       39       40
 2021-03-24 21:02:22         30       20       0       25       40

My searches for a solution led me to

data <- sort(data$date, decreasing=FALSE)

It doesn't seem to work. It doesn't sort - instead it creates a sorted vector of the dates. As you can see, the time next to the date is important and I need to keep it. Perhaps this is the issue. I can't seem to find a solution using the timeSeries package either. I also tried the arrange() function in dplyr.

data <- dplyr::arrange(data, date)

This is closer to what I want. It is certainly sorted by year, month, and day. However, I did mention the time was important. This is something the function does not sort. I see an entry from an earlier time point will lower down the data.

1 Answers

Chances are your date column is character string and not a date/time object.

If you are using the dplyr package try this:

data <- dplyr::arrange(data, as.POSIXct(date))

or in base R:

data[order(as.POSIXct(data$date)),]
Related