Formatting a Date in R Without Leading Zeros

Formatting a date in R without leading zeros

Just remove the leading zeros at the end:

gsub(" 0", " ", format(as.Date("1998-09-02"), "%Y, %m, %d"))
## [1] "1998, 9, 2"

Use %e to obtain a leading space instead of a leading zero.

date format without leading zeros - R

We can use strftime.

strftime(as.Date(inp, format="%d/%m/%Y"), format="%d/%m/%Y")
# [1] "15/01/2019" "05/05/2019"

Data

inp <- c("15/1/2019", "5/5/2019")

Converting to a standard as.Date date-time then back again, without leading zeros

Here is a way to go straight from date_num to your desired result, using the chron package.

paste(chron::month.day.year(date_num), collapse = "/")
# [1] "9/5/2008"

This also works nicely for multiple dates. The code is slightly different as we need do.call() here.

do.call(paste, c(chron::month.day.year(Sys.Date()-0:3), sep = "/"))
# [1] "10/9/2015" "10/8/2015" "10/7/2015" "10/6/2015"

How to convert to date a character with no leading zeros at months and days?

We can use anydate from anytime

anytime::anydate(dates)
#[1] "2021-02-11"
#[2]"2021-02-17"
#[3] "2021-02-26"
#[4] "2021-02-07"
#[5] "2021-03-12"
#[6] "2021-03-18"
#[7] "2021-03-02"

With as.Date, the format would be %m/%d/%Y

as.Date(dates, format = "%m/%d/%Y")
#[1] "2021-02-11" "2021-02-17" "2021-02-26" "2021-02-07" "2021-03-12" "2021-03-18" "2021-03-02"

No leading zeros for months R

A solution with sub:

x <- as.Date("2005-09-02")
sub("..0?(.+)-0?(.+)-0?(.+)", "\\3/\\2/\\1", x)
# [1] "2/9/5"

Remove leading zeros from single digit months in year-month values

Using gsub:

gsub("Y0", "Y", format(as.Date(lubridate::ym(year_months)), "%YY%mm"))
# [1] "2021Y12m" "2021Y11m" "2021Y2m" "2021Y1m"

Or stringr::str_replace_all:

stringr::str_replace_all(format(as.Date(lubridate::ym(year_months)), "%YY%mm"), "Y0", "Y")
# [1] "2021Y12m" "2021Y11m" "2021Y2m" "2021Y1m"

How to remove leading zero from %m for x axis in ggplot2

You can do this with a simple change to your strftime format string. However, it depends on your platform (Unix or Windows).

Windows

Insert a pound sign (#) before the m:

p + scale_x_date(date_labels = "%#m/%d", #this generated dates like: 2/15, 3/15, etc
date_breaks = "1 week",
expand = expand_scale(0,0))

Unix

Insert a minus sign (-) before the m:

p + scale_x_date(date_labels = "%-m/%d", #this generated dates like: 2/15, 3/15, etc
date_breaks = "1 week",
expand = expand_scale(0,0))


Related Topics



Leave a reply



Submit