-1

I have a data like this, From the string of time Period Column, I want separate them and save them in Week, Month and Year columns which are highlighted in yellow. Please find the data below

Shunty
  • 3
  • 3

2 Answers2

1

You can use extract:

library(tidyr)
df %>%
  extract(Date,
          into = c("Day", "Month", "Year"),
          regex = ".*(\\d+)-(\\d+)-(\\d+)")
  Day Month Year
1   1     1 2018
2   5     2 2021

If you want to keep the original dates, use remove = FALSE:

df %>%
  extract(Date,
          into = c("Day", "Month", "Year"),
          regex = ".*(\\d+)-(\\d+)-(\\d+)",
          remove = FALSE)

Data:

df <- data.frame(
  Date = c("1-1-2018", "15-2-2021")
)
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
0

Another way would be to use lubridate library:

library(dplyr)
df %>%
  mutate(Date = lubridate::dmy(Date)) %>% 
  mutate(Day = lubridate::day(Date),
         Month = lubridate::month(Date),
         Year = lubridate::year(Date))


# Date Day Month Year
# 1 2018-01-01   1     1 2018
# 2 2021-02-15  15     2 2021

data:

df <- data.frame(
  Date = c("1-1-2018", "15-2-2021")
)
AlexB
  • 3,061
  • 2
  • 17
  • 19