In this table I have a column named Date and I want to add 3 more columns as Year, Month, and Day and extract the information from the Date column itself but the class of the Date column is factor.
How can I do that in R using lubridate
.
In this table I have a column named Date and I want to add 3 more columns as Year, Month, and Day and extract the information from the Date column itself but the class of the Date column is factor.
How can I do that in R using lubridate
.
Using lubridate
, we can use mdy_hm
to convert to datetime object and then extract the year
, month
, and day
library(lubridate)
v1 <- mdy_hm(df1$Date)
df2 <- transform(df1, Year = year(v1), Month = month.abb[month(v1)], Day = day(v1))
df2
# Date Year Month Day
#1 3/30/2008 0:04 2008 Mar 30
#2 10/15/2009 10:15 2009 Oct 15
df1 <- data.frame(Date = c("3/30/2008 0:04", "10/15/2009 10:15"))