How to sort date column in R from latest to earliest and then read the first entry as a vector?

Viewed 49

For example i have a dataset that looks like this

 ID| Date Column| Col3|Col4
 1    2021-02-06    Y    N
 2    2021-03-02    Y    N
 3    2020-01-12    N    N
 4    2021-04-07    Y    Y
 5    2020-03-04    Y    Y

My outcome should be

x <- ("2021-04-07")
2 Answers

Convert to Date class and get the max

x <- max(as.Date(df1[["Date Column"]]))
x
#[1] "2021-04-07"

data

df1 <- structure(list(ID = 1:5, `Date Column` = c("2021-02-06", "2021-03-02", 
"2020-01-12", "2021-04-07", "2020-03-04"), Col3 = c("Y", "Y", 
"N", "Y", "Y"), Col4 = c("N", "N", "N", "Y", "Y")), 
class = "data.frame", row.names = c(NA, 
-5L))

We can also do max over character column Date Column, i.e.,

> with(
+   df,
+   max(`Date Column`)
+ )
[1] "2021-04-07"
Related