No leading zeros for months R [duplicate]

和自甴很熟 提交于 2019-12-23 13:33:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!