我具有以下日期为(YYYY-MM-DD)的数据集:
> dates
[1] "20180412" "20180424" "20180506" "20180518" "20180530" "20180611" "20180623" "20180705" "20180717" "20180729"
我想将它们转换为:
DD-MMM-YYYY,但月份为文本。例如,20180412
应该变成12Apr2018
关于如何进行的任何建议?
M
答案 0 :(得分:3)
您需要先将文本字符串解析为Date
对象,然后根据自己的喜好 format 这些Date
对象以具有不同的样式文字输出:
R> library(anytime) ## one easy way to parse dates and times
R> dates <- anydate(c("20180412", "20180424", "20180506", "20180518", "20180530",
+ "20180611", "20180623", "20180705", "20180717", "20180729"))
R> dates
[1] "2018-04-12" "2018-04-24" "2018-05-06" "2018-05-18" "2018-05-30"
[6] "2018-06-11" "2018-06-23" "2018-07-05" "2018-07-17" "2018-07-29"
R>
R> txtdates <- format(dates, "%d%b%Y")
R> txtdates
[1] "12Apr2018" "24Apr2018" "06May2018" "18May2018" "30May2018"
[6] "11Jun2018" "23Jun2018" "05Jul2018" "17Jul2018" "29Jul2018"
R>
答案 1 :(得分:3)
您可以使用as.Date()
和format()
函数:
dts <- c("20180412", "20180424", "20180506", "20180518", "20180530",
"20180611", "20180623")
format(as.Date(dts, format = "%Y%m%d"), "%d%b%Y")
更多信息here
答案 2 :(得分:2)
只需使用ShaderChunk.ts
和as.POSIXct
:
as.format
输出:
dates <- c("20180412", "20180424", "20180506")
format(as.POSIXct(dates, format="%Y%m%d"),format="%d%b%y")
答案 3 :(得分:1)
您可以尝试这样的事情:
# print today's date
today <- Sys.Date()
format(today, format="%B %d %Y") "June 20 2007"
其中,以下符号可与format()函数一起使用以打印日期1