5

format() in R does not have an obvious option to display the month without leading 0 (and the same with the year). Is there another way to get this result? The solution should allow the user to flexibly choose whether 0s are to be omitted only for the day or the month or the year or for any combination.

in: as.Date("2005-09-02")

out: 2/9/5

or 0 only removed for month:

out: 2/9/05

Andri Signorell
  • 1,279
  • 12
  • 23

3 Answers3

8

You can try this.

x <- as.Date(c("2005-09-02", "2005-10-20", "2010-10-20"))

gsub("0(\\d)", "\\1", format(x, "%d/%m/%y"))
# [1] "2/9/5"    "20/10/5"  "20/10/10"

But keep in mind that doing this on a vector of dates from different centuries will make things a bit confusing when you go back to look at them later.

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
2

A solution with sub:

x <- as.Date("2005-09-02")
sub("..0?(.+)-0?(.+)-0?(.+)", "\\3/\\2/\\1", x)
# [1] "2/9/5"
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
-4

You can do this but you need to set it as a character because that format is not an actual date format.

X = "2005-09-02"
date = paste(substr(X,10,10),"/",substr(X,7,7),"/",substr(X,4,4),sep='')
user2600629
  • 559
  • 6
  • 16