问题
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
回答1:
A solution with sub:
x <- as.Date("2005-09-02")
sub("..0?(.+)-0?(.+)-0?(.+)", "\\3/\\2/\\1", x)
# [1] "2/9/5"
回答2:
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.
回答3:
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='')
来源:https://stackoverflow.com/questions/27584346/no-leading-zeros-for-months-r