从R中的现有日期变量创建适当的日期变量

时间:2014-03-29 10:25:42

标签: r date

我有一个带有日期变量(死亡日期)的数据框'rta',数据以DD / MM / YY,D / M / YY,DD / M / YY,D / MM / YY等多种格式输入,DD / MM,D / MM,D / M,DD / M.

rta$date.of.death<-c('12/12/08' ,'1/10/08','4/3/08','24/5/08','23/4','11/11','1/12')

幸运的是,所有日期都属于2008年。 我想把这个变量变成DD / MM / YYYY的统一格式,例如12/12/2008。怎么这样做?

2 个答案:

答案 0 :(得分:0)

您可以使用这种快速的方式:

rta <- data.frame(date.of.death=c('12/12/08' ,'1/10/08', '4/3/08',
                                  '24/5/08','23/4','11/11','1/12'),
                  stringsAsFactors=F)

# append '/08' to the dates without year
noYear <- grep('.+/.+/.+',rta$date.of.death,invert=TRUE)
rta$date.of.death[noYear] <- paste(rta$date.of.death[noYear],'08',sep='/')

# convert the strings into POSIXct dates
dates <- as.POSIXct(rta$date.of.death, format='%d/%m/%y')
# turn the dates into strings having format: DD/MM/YYYY
rta$date.of.death <- format(dates,format='%d/%m/%Y')

> rta$date.of.death
[1] "12/12/2008" "01/10/2008" "04/03/2008" "24/05/2008" "23/04/2008" "11/11/2008" "01/12/2008"

注意:
此代码假定没有日期具有四位数年份,例如01/01/2008

答案 1 :(得分:0)

试试这个:

as.Date(paste0(rta$date.of.death, "/08"), "%d/%m/%y")

[1] "2008-12-12" "2008-10-01" "2008-03-04" "2008-05-24" "2008-04-23"
[6] "2008-11-11" "2008-12-01"
相关问题