How to Find Earliest Date in a Column in R?

A: You can use the min() function to find the earliest date in a column of dates. Simply pass the column name as an argument to the min() function and it will return the earliest date in the column. You can also use the max() function to find the latest date in the column.


You can use the following methods to find the earliest date in a column of a data frame in R:

Method 1: Find Earliest Date in Column

min(df$date_column)

Method 2: Find Row with Earliest Date in Column

df[which.min(df$date), ]

The following examples shows how to use this syntax in practice with the following data frame:

#create data frame
df <- data.frame(date=as.Date(c('2022-04-01','2022-02-12','2022-06-13','2022-02-04',
                                '2022-07-01','2022-02-19','2022-12-03','2022-04-04')),
                 sales = c(12, 15, 24, 24, 14, 19, 12, 38))

#view data frame
df

        date sales
1 2022-04-01    12
2 2022-02-12    15
3 2022-06-13    24
4 2022-02-04    24
5 2022-07-01    14
6 2022-02-19    19
7 2022-12-03    12
8 2022-04-04    38

Example 1: Find Earliest Date in Column

We can use the following code to find the earliest date in the date column of the data frame:

#find earliest date in 'date' column
min(df$date)

[1] "2022-02-04"

From the output we can see that the earliest date in the date column is 2/4/2022.

Note: If you want to find the most recent date, simply change min to max in the code.

Example 2: Find Row with Earliest Date in Column

We can use the following code to find the row with the earliest date in the date column of the data frame:

#find row with earliest date in 'date' column
df[which.min(df$date), ]

        date sales
4 2022-02-04    24

The output displays the entire row that contains the earliest date in the date column.

For example, we can see the following values in this row:

  • date: 2022-02-04
  • sales: 24

Note: If you want to find the row with the most recent date, simply change which.min() to which.max() in the code.

The following tutorials explain how to perform other common operations in R:

 

x