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.
Asked
Active
Viewed 142 times
1 Answers
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, format
the 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