想更改日期格式。我的数据框如下所示,并希望将所有日期格式更改为"%d/%m/%Y"
。将日期格式更改为“%d /%m /%Y”
DF:
id bdate wdate ddate
1 09/09/09 12/10/09 2009-09-27
想更改日期格式。我的数据框如下所示,并希望将所有日期格式更改为"%d/%m/%Y"
。将日期格式更改为“%d /%m /%Y”
DF:
id bdate wdate ddate
1 09/09/09 12/10/09 2009-09-27
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")
df$ddate <- format(as.Date(df$ddate), "%d/%m/%Y")
默认R
作用是把字符串作为因素。当然,个别设置可能与默认值不同。将变量值更改为character
,然后将其转换为date
是一种很好的做法。我经常使用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"
花莲CA ...它应该做的伎俩......
它几乎取决于你实际上在你的'data.frame'。这个字段是'Date','character','factor'吗?如果你想改变'data.frame'的打印方式,那么你可以重载一个'print'方法('print.Date'或'print.POSIXlt')。 – Marek 2010-05-14 10:15:33
嗨马雷克, 这些是日期! Bazon – Bazon 2010-05-17 03:06:43