0

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

David95
  • 35
  • 5

3 Answers3

0

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))
  
}
0

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
Quinten
  • 35,235
  • 5
  • 20
  • 53
  • Thank you! How do i get a new column with the numbers of each row, too? Example: 2022-01-01 ->1 2022-01-03 ->2 – David95 Apr 28 '22 at 08:48
  • @David95, You mean you want a new column that shows the index of every row? – Quinten Apr 28 '22 at 09:00
  • In the colum of dates are no weekends. I like to have the number of each day. So that the first Monday- Friday is 1-5 and the next Monday has the number 6 instead of 8. I want this for each month, the number of days for every month. So when the month changes the counting of days starts new – David95 Apr 28 '22 at 09:06
  • @David95, use this `df[, "day"] <- format(df[,"date"], "%d") ` for the days. – Quinten Apr 28 '22 at 09:09
  • @David95, I would suggest making a new question for that part, because that is something really different and good to ask in a new question. – Quinten Apr 28 '22 at 09:12
0
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
Chamkrai
  • 5,912
  • 1
  • 4
  • 14