'How do i get the number of each month? [closed]

I have a data frame with a column of date objects. How can i get a new column with the number of a month? example: January -> 1, february -> 2 ...

I need a new column with the numbers of each day of the month, too. example: 2022-01-01 -> 1 , 2022-01-02 - 2



Solution 1:[1]

You can use the following code:

df = data.frame(date = as.Date(c("2022-01-01", "2022-01-02")))
df[, "month"] <- format(df[,"date"], "%m")
df

Output:

        date month
1 2022-01-01    01
2 2022-01-02    01

Solution 2:[2]

I'm sure there are date object-specific solutions in R, but I've never used them. A base R solution:

splitDates <- function( date ) {
  
  day <- gsub('^0+','',unlist(strsplit(date,'-'))[2])
  month <- gsub('^0+','',unlist(strsplit(date,'-'))[3])
  
  return(list(day,
              month))
  
}

Solution 3:[3]

require(tidyverse)
require(lubridate) 

Example data:

# A tibble: 13 × 1
   date      
   <date>    
 1 2022-04-28
 2 2022-05-28
 3 2022-06-28
 4 2022-07-28
 5 2022-08-28
 6 2022-09-28
 7 2022-10-28
 8 2022-11-28
 9 2022-12-28
10 2023-01-28
11 2023-02-28
12 2023-03-28
13 2023-04-28

A possible solution:

  df %>%
  mutate(
    month = month(date),
    month_name = month(date, label = TRUE, abbr = FALSE),
    day = day(date),
    week = week(date)
  )

The output:

# A tibble: 13 × 5
   date       month month_name   day  week
   <date>     <dbl> <ord>      <int> <dbl>
 1 2022-04-28     4 April         28    17
 2 2022-05-28     5 May           28    22
 3 2022-06-28     6 June          28    26
 4 2022-07-28     7 July          28    30
 5 2022-08-28     8 August        28    35
 6 2022-09-28     9 September     28    39
 7 2022-10-28    10 October       28    43
 8 2022-11-28    11 November      28    48
 9 2022-12-28    12 December      28    52
10 2023-01-28     1 January       28     4
11 2023-02-28     2 February      28     9
12 2023-03-28     3 March         28    13
13 2023-04-28     4 April         28    17

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Quinten
Solution 2 undercover_camel
Solution 3 Tom Hoel