0
votes

I have a dataset with multiple columns but I'd like to change the order in chronological order by date!

This is a really bad example but would there be a code to r

Station year ID
1 2020 D
2 2019 C
3 2017 A
4 2018 B

This is a really bad example but would there be a code to reorder by date oldest to newest?

Station year ID
3 2017 A
4 2018 B
2 2019 C
1 2020 D

To look something like this!

Any help would be amazing! :) Thank you

2

2 Answers

0
votes

Well... "2020" is not a date, and you can order the column as regular integer.

But, if you had dates like "2020-01-25"... transforming strings to dates is easy as...

df <- tibble(n = c(1,2,3,4),
             dt = c("2020-01-01","2019-01-01","2017-01-01", "2018-01-01"),
             l = c("D","C","A","B"))

df <- df %>% 
  mutate(
    dt = as.Date(dt)
  ) %>% 
  arrange(
    dt
  )

enter image description here

0
votes

Use ymd () function from lubridate package to bring dt to date format and year () to extract the year. With this format you can sort your dates with arrange

library(dplyr)
library(lubridate)
# data borrowed from abreums
df <- tibble(n = c(1,2,3,4),
             dt = c("2020-01-01","2019-01-01","2017-01-01", "2018-01-01"),
             l = c("D","C","A","B"))

df1 <- df %>% 
  mutate(dt = ymd(dt),           # "2020-01-01"
         dt = year(dt)) %>%      # "2020"
  arrange(dt)

enter image description here