想要更改日期格式。我的数据框如下所示,并希望将所有日期格式更改为"%d/%m/%Y"
。
DF:
id bdate wdate ddate
1 09/09/09 12/10/09 2009-09-27
答案 0 :(得分:32)
df$ddate <- format(as.Date(df$ddate), "%d/%m/%Y")
答案 1 :(得分:14)
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")
答案 2 :(得分:2)
默认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"
C'est ca ...它应该做的伎俩...