v_head
v_head

Reputation: 805

parsing dates in R

I have this input: 2020-03-11 and I want to return 03-11, How can I do that in R?. For example, if I want to have only month, I can assign the month this way: Month=lubridate::month(data)

Upvotes: 0

Views: 97

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269451

Here are a few ways. All are vectorized, i.e. x can be a vector of such strings. No packages are used.

x <- "2020-03-11"  # input

substring(x, 6)

sub("\\d+-", "", x)

trimws(trimws(x, "left", "\\d"), "left", "-")

format(as.Date(x), "%m-%d")

A different approach is to create an S3 subclass of Date that represents a Date but displays just the month and day storing the full date so that it is recoverable. as.md constructs an object of this new class, as.Date.md converts it back to Date class and format.md formats it. If we print such as object it will look for print.md but we have not defined it so it will use print.Date, the print method of the super class of md, and that method calls format invoking format.md.

as.md <- function(x, ...) structure(as.Date(x), class = c("md", "Date"))
as.Date.md <- function(x, ...) structure(x, class = "Date")
format.md <- function(x, format = "%m-%d", ...) format(as.Date(x), format = format, ...)

y <- as.md(x)

y
## [1] "03-11"

as.Date(y)  # recover the full date
##[1] "2020-03-11"

data.frame(x, y)
##            x     y
## 1 2020-03-11 03-11

Upvotes: 2

Yellow_truffle
Yellow_truffle

Reputation: 923

One easy way to do this is:

library(lubridate)
x <- "2020-03-11"
month <-month(x)
day <- day(x)
paste(month,"-",day)

and here is the result:

"3 - 11"

So, basically, I used lubridate to extract day and month and then used paste function to put those two together.

Another alternative is to use the code below (no lubridate):

format(as.Date(x), "%m-%d")

here is the result:

"03-11"

Upvotes: 1

Related Questions