-1

I have 500 rows with date column and the first row is 2018-10-17. I want to create separate columns for day,month and year. The class of date column is Factor.

Sotos
  • 51,121
  • 6
  • 32
  • 66
Akshayd978
  • 19
  • 2

1 Answers1

0

You can use str_extract from the library stringr:

date <- "2018-10-17"

library(stringr)
df <- data.frame(
  year = str_extract(date, "^\\d{4}"),
  month = str_extract(date, "(?<=-)\\d{2}(?=-)"),
  day = str_extract(date, "(?<=-)\\d{2}$")
)

df
  year month day
1 2018    10  17

Alternatively, formatthe dates as required:

df <- data.frame(
  year = format(as.Date(date, "%Y-%m-%d"), "%Y"),
  month = format(as.Date(date, "%Y-%m-%d"), "%m"),
  day = format(as.Date(date, "%Y-%m-%d"), "%d")
)
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34