如何用as.Date转换字符串但显示为dd/mm/yyyy
How to convert character string with as.Date but display as dd/mm/yyyy
抱歉,我似乎找不到解决这个看似基本问题的方法。
这个
p %>% mutate(date = as.Date(mr_daterd, format = '%d/%m/%Y'), mr_daterd = mr_daterd)
给予
mr_daterd date
1 28/03/2013 2013-03-28
2 10/01/2009 2009-01-10
3 16/09/2005 2005-09-16
4 28/03/2013 2013-03-28
5 28/03/2013 2013-03-28
6 28/03/2013 2013-03-28
我需要 p$date
才能成为 dd/mm/yyyy
。
p <- structure(list(mr_daterd = c("18/03/2011", "10/01/2009", "10/01/2009",
"11/03/2004", "10/01/2009", "18/03/2011", "16/09/2005", "10/01/2009",
"18/03/2011", "10/01/2009", "18/03/2011", "18/03/2011", "28/03/2013 ",
"28/03/2013 ", "10/01/2009")), row.names = c(NA, -15L), class = "data.frame")
一种实现您想要的方法是创建您自己的 S3 class。这并不像听起来那么难,只需要两行代码:
as.myDate <- function(x, ...) `class<-`(as.Date(x, ...), c("myDate", "Date"))
format.myDate <- function(x, ...) format(`class<-`(x, "Date"), "%d/%m/%Y")
然后您可以执行以下操作:
p$date <- as.myDate(p$mr_daterd, format = "%d/%m/%Y")
p
#> mr_daterd date
#> 1 18/03/2011 18/03/2011
#> 2 10/01/2009 10/01/2009
#> 3 10/01/2009 10/01/2009
#> 4 11/03/2004 11/03/2004
#> 5 10/01/2009 10/01/2009
#> 6 18/03/2011 18/03/2011
#> 7 16/09/2005 16/09/2005
#> 8 10/01/2009 10/01/2009
#> 9 18/03/2011 18/03/2011
#> 10 10/01/2009 10/01/2009
#> 11 18/03/2011 18/03/2011
#> 12 18/03/2011 18/03/2011
#> 13 28/03/2013 28/03/2013
#> 14 28/03/2013 28/03/2013
#> 15 10/01/2009 10/01/2009
这个新的 class 继承了“Date”的所有其他通用函数,因此其行为仍然与 Date 对象相同:
difftime(p$date[2], p$date[1])
#> Time difference of -797 days
plot(p$date, rnorm(15))
抱歉,我似乎找不到解决这个看似基本问题的方法。
这个
p %>% mutate(date = as.Date(mr_daterd, format = '%d/%m/%Y'), mr_daterd = mr_daterd)
给予
mr_daterd date
1 28/03/2013 2013-03-28
2 10/01/2009 2009-01-10
3 16/09/2005 2005-09-16
4 28/03/2013 2013-03-28
5 28/03/2013 2013-03-28
6 28/03/2013 2013-03-28
我需要 p$date
才能成为 dd/mm/yyyy
。
p <- structure(list(mr_daterd = c("18/03/2011", "10/01/2009", "10/01/2009",
"11/03/2004", "10/01/2009", "18/03/2011", "16/09/2005", "10/01/2009",
"18/03/2011", "10/01/2009", "18/03/2011", "18/03/2011", "28/03/2013 ",
"28/03/2013 ", "10/01/2009")), row.names = c(NA, -15L), class = "data.frame")
一种实现您想要的方法是创建您自己的 S3 class。这并不像听起来那么难,只需要两行代码:
as.myDate <- function(x, ...) `class<-`(as.Date(x, ...), c("myDate", "Date"))
format.myDate <- function(x, ...) format(`class<-`(x, "Date"), "%d/%m/%Y")
然后您可以执行以下操作:
p$date <- as.myDate(p$mr_daterd, format = "%d/%m/%Y")
p
#> mr_daterd date
#> 1 18/03/2011 18/03/2011
#> 2 10/01/2009 10/01/2009
#> 3 10/01/2009 10/01/2009
#> 4 11/03/2004 11/03/2004
#> 5 10/01/2009 10/01/2009
#> 6 18/03/2011 18/03/2011
#> 7 16/09/2005 16/09/2005
#> 8 10/01/2009 10/01/2009
#> 9 18/03/2011 18/03/2011
#> 10 10/01/2009 10/01/2009
#> 11 18/03/2011 18/03/2011
#> 12 18/03/2011 18/03/2011
#> 13 28/03/2013 28/03/2013
#> 14 28/03/2013 28/03/2013
#> 15 10/01/2009 10/01/2009
这个新的 class 继承了“Date”的所有其他通用函数,因此其行为仍然与 Date 对象相同:
difftime(p$date[2], p$date[1])
#> Time difference of -797 days
plot(p$date, rnorm(15))