user3115933
user3115933

Reputation: 4463

How to extract Month and Day from Date in R and convert it as a date type?

I am Rstudio for my R sessions and I have the following R codes:

d1 <- read.csv("mydata.csv", stringsAsFactors = FALSE, header = TRUE)

d2 <- d1 %>% 
      mutate(PickUpDate = ymd(PickUpDate))

str(d2$PickUpDate)

output of last line of code above is as follows:

Date[1:14258], format: "2016-10-21" "2016-07-15" "2016-07-01" "2016-07-01" "2016-07-01" "2016-07-01" ...

I need an additional column (let's call it MthDD) to the dataframe d2, which will be the Month and Day of the "PickUpDate" column. So, column MthDD need to be in the format mm-dd but most importantly, it should still be of the date type.

How can I achieve this?

UPDATE: I have tried the following but it outputs the new column as a character type. I need the column to be of the date type so that I can use it as the x-axis component of a plot.

d2$MthDD <- format(as.Date(d2$PickUpDate), "%m-%d")

Upvotes: 6

Views: 15554

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270348

Date objects do not display as mm-dd. You can create a character string with that representation but it will no longer be of Date class -- it will be of character class.

If you want an object that displays as mm-dd and still acts like a Date object what you can do is create a new S3 subclass of Date that displays in the way you want and use that. Here we create a subclass of Date called mmdd with an as.mmdd generic, an as.mmdd.Date method, an as.Date.mmdd method and a format.mmdd method. The last one will be used when displaying it. mmdd will inherit methods from Date class but you may still need to define additional methods depending on what else you want to do -- you may need to experiment a bit.

as.mmdd <- function(x, ...) UseMethod("as.mmdd")
as.mmdd.Date <- function(x, ...) structure(x, class = c("mmdd", "Date"))

as.Date.mmdd <- function(x, ...) structure(x, class = "Date")

format.mmdd <- function(x, format = "%m-%d", ...) format(as.Date(x), format = format, ...)

DF <- data.frame(x = as.Date("2018-03-26") + 0:2) # test data

DF2 <- transform(DF, y = as.mmdd(x))

giving:

> DF2
           x     y
1 2018-03-26 03-26
2 2018-03-27 03-27
3 2018-03-28 03-28

> class(DF2$y)
[1] "mmdd" "Date"

> as.Date(DF2$y)
[1] "2018-03-26" "2018-03-27" "2018-03-28"

Upvotes: 5

Nordsted
Nordsted

Reputation: 107

Try using this:

PickUpDate2 <- format(PickUpDate,"%m-%d")
PickUpDate2 <- as.Date(PickUpDate2, "%m-%d")

This should work, and you should be able to bind_cols afterwards, or just add it to the data frame right away, as you proposed in the code you provided. So the code should be substituted to be:

d2$PickUpDate2 <- format(d2$PickUpDate,"%m-%d")
d2$PickUpDate2 <- as.Date(d2$PickUpDate2, "%m-%d")

Upvotes: 2

Related Questions