想要改变日期格式。我的数据框如下所示,想要将所有日期格式更改为"%d/%m/%Y"
。
df:
id bdate wdate ddate
1 09/09/09 12/10/09 2009-09-27
想要改变日期格式。我的数据框如下所示,想要将所有日期格式更改为"%d/%m/%Y"
。
df:
id bdate wdate ddate
1 09/09/09 12/10/09 2009-09-27
df$ddate <- format(as.Date(df$ddate), "%d/%m/%Y")
df$ddate<-strftime(df$ddate,"%d/%m/%Y")
df$bdate<-strftime(strptime(df$bdate,"%d/%m/%y"),"%d/%m/%Y")
df$wdate<-strftime(strptime(df$wdate,"%d/%m/%y"),"%d/%m/%Y")
默认情况下,R
会将字符串视为因子。当然,个人设置可能与默认设置不同。更好的做法是将变量值更改为字符
,然后将其转换为日期
。我经常使用chron
包-它很好用、简单而且最重要的是,它能够胜任任务。这个包唯一的缺点在于时区处理。
如果您没有安装chron
,请执行以下操作:
install.packages("chron")
# load it
library(chron)
# make dummy data
bdate <- c("09/09/09", "12/05/10", "23/2/09")
wdate <- c("12/10/09", "05/01/07", "19/7/07")
ddate <- c("2009-09-27", "2007-05-18", "2009-09-02")
# notice the last argument, it will not allow creation of factors!
dtf <- data.frame(id = 1:3, bdate, wdate, ddate, stringsAsFactors = FALSE)
# since we have characters, we can do:
foo <- transform(dtf, bdate = chron(bdate, format = "d/m/Y"), wdate = chron(wdate, format = "d/m/Y"), ddate = chron(ddate, format = "y-m-d"))
# check the classes
sapply(foo, class)
# $id
# [1] "integer"
# $bdate
# [1] "dates" "times"
# $wdate
# [1] "dates" "times"
# $ddate
# [1] "dates" "times"
就是这样...这应该能解决问题...
data.frame
中实际包含了什么数据类型。这些字段是Date
、character
还是factor
?如果你想要改变data.frame
打印的方式,那么可以重载其中一个print
方法(print.Date
或print.POSIXlt
)。 - Marek