[英]Convert character to date in R while changing date default format
我在R中具有以下字符變量:
> d <- "06/01/2018"
> class(d)
> "character"
我想將其轉換為日期,更改默認的日期格式,並將數據類型保留為日期,所以我開始於:
> d <- as.Date(s, format = "%m/%d/%Y")
> class(d)
> "Date"
一切都很好,但是默認日期格式以年份而不是月份開頭-我希望它以月份開頭:
> d
> "2018-06-01"
因此,如果我再次格式化,日期從現在的月份開始,但是它將變量變回字符!
> d <- format(d, "%m/%d/%Y")
> d
> "06/01/2018"
> class(d)
> character
如何在不轉換回字符的情況下以新的(非默認)格式將d保留為Date?
1)計時打印。 print.Date
將始終使用yyyy-mm-dd,但chron將使用mm / dd / yy:
library(chron)
d <- "06/01/2018"
as.chron(d)
## [1] 06/01/18
2)子類您可以定義Date的S3子類,以所需的方式顯示:
as.subDate <- function(x, ...) UseMethod("as.subDate")
as.subDate.character <- function(x, ...) {
structure(as.Date(x, "%m/%d/%Y"), class = c("subDate", "Date"))
}
format.subDate <- function(x, ...) format.Date(x, "%m/%d/%Y")
as.subDate(d)
## [1] "06/01/2018"
您可能需要根據自己的需要添加更多方法。
通過在控制台上僅輸入變量名,將使用默認參數print
進行print
。 如果要使用其他格式,請更改Date
print
方式:
Sys.Date()
# [1] "2018-06-04
print.Date <- function (x, max = NULL, ...) {
if (is.null(max))
max <- getOption("max.print", 9999L)
n_printed <- min(max, length(x))
formatted <- strftime(x[seq_len(n_printed)], format = "%m/%d/%Y")
print(formatted, max = max, ...)
if (max < length(x)) {
cat(" [ reached getOption(\"max.print\") -- omitted",
length(x) - max, "entries ]\n")
} else if (length(x) == 0L) {
cat(class(x)[1L], "of length 0\n")
}
invisible(x)
}
Sys.Date()
# [1] "06/04/2018"
這只是標准的print.Date
函數,需要進行一些編輯。
但是我必須對此發表評論:
我想將其轉換為日期,更改默認日期格式,並將數據類型保留為日期
Date
向量沒有格式。 將格式轉換為character
向量時可以使用格式(這是print
作用),但是Date
實際上只是具有不同類的integer
。 整數給出了經過紀元(1970-01-01)的天數:
x <- 1
x
# [1] 1
class(x) <- "Date"
x
# [1] "1970-01-02"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.