1

enter image description here

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Try `v1 <- mdy_hm(df1$Date); transform(df1, Year = year(v1), Month = month(v1), Day = day(v1))` – akrun Jul 20 '17 at 06:17

1 Answers1

3

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

data

df1 <- data.frame(Date = c("3/30/2008 0:04", "10/15/2009 10:15"))
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks a lot Akrun, its working but if I want to convert that Date column into a Date fromat without creating a new column as mentioned by you 'v1' , how to do that, if u can help please... – user8335527 Jul 20 '17 at 06:33
  • @user8335527 Then just do `df1$Date <- as.Date(df1$Date, "%m/%d/%Y")` – akrun Jul 20 '17 at 06:36
  • but in Date column time is also there that's why its not working.. I'm getting error: "Error in as.Date.default(BAF_Prod_ChartApr08_Jun17, "%m/%d/%y") : do not know how to convert 'BAF_Prod_ChartApr08_Jun17' to class “Date” – user8335527 Jul 20 '17 at 06:44
  • @user8335527 Based on the example you showed in image and the one I showed in 'data' it is working for me – akrun Jul 20 '17 at 06:46
  • A slight refinement, can do `month(v1, abbr=TRUE)`, instead of `month.abb[month(v1)]` – Remko Duursma Jul 20 '17 at 06:51