No leading zeros for R months
format()
in R has no obvious ability to display the month without a leading 0 (and the same with the year). Is there any other way to get this result?
in: as.Date("2005-09-02")
out: 2/9/5
or 0 only the month is removed:
out: 2/9/05
+3
Andri Signorell
source
to share
3 answers
Solution with sub
:
x <- as.Date("2005-09-02")
sub("..0?(.+)-0?(.+)-0?(.+)", "\\3/\\2/\\1", x)
# [1] "2/9/5"
+2
Sven Hohenstein
source
to share
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 ages will be a little confusing when you come back to look at them later.
+6
Rich scriven
source
to share
You can do this, but you need to set it as a character, because this format is not the actual date format.
X = "2005-09-02"
date = paste(substr(X,10,10),"/",substr(X,7,7),"/",substr(X,4,4),sep='')
-2
user2600629
source
to share