2

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.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
AcidCatfish
  • 192
  • 8
  • 1
    `dplyr::arrange()` should do exactly what you want. If it doesn’t, that suggests that the column doesn’t actually contain date objects, but perhaps just plain string representations of dates, which won’t necessarily sort by time. Can you confirm what variable type the column contains? – Michael MacAskill Jun 26 '21 at 00:06
  • 1
    ```dplyr::arrange()``` ended up working after I cleared all first. I think messing around with it before took it out of the date objects. – AcidCatfish Jun 26 '21 at 00:23

1 Answers1

2

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)),]
Dave2e
  • 22,192
  • 18
  • 42
  • 50