>我在R中有以下字符变量:
> d <- "06/01/2018"
> class(d)
> "character"
我想将其转换为日期,更改默认日期格式,并将数据类型保留为 Date,所以我从:
> 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(chronprint.Date
将始终使用yyyy-mm-dd,但chron将使用mm/dd/yy:
library(chron)
d <- "06/01/2018"
as.chron(d)
## [1] 06/01/18
2(子类 您可以定义以所需方式显示的日期的 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
的工作方式:
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 0n")
}
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"