我有一个数据框' rta'有两个日期变量" Date.Time of Accident"和" Date.Time。死亡"。变量' Date.Time.Death'将日期和时间用空格分隔,时间为24小时格式,但在分钟时不均匀。类似地,另一个变量Date.Time.Accident也只是这种格式。
rta <- data.frame(DMYT.Death = c('2008-12-30 10.15','2008-12-15 23','2008-12-15 18.15','2008-12-26 17','2008-12-21 14.45','2008-12-19 23'),stringsAsFactors=F)
我想把这个变量变成YYYY-MM-DD hh:mm的统一格式,例如2008-12-30 10:15,它可以用来计算两个日期变量的生存期。怎么这样做?
答案 0 :(得分:0)
rta
## datevar
## 1 2008-12-30 10.15
## 2 2008-12-15 23
## 3 2008-12-15 18.15
## 4 2008-12-26 17
## 5 2008-12-21 14.45
## 6 2008-12-19 23
# First we add the 'minutes' to strings where they are missing.
rta$datevar[!grepl(".*\\..*", rta$datevar)] <- paste0(rta$datevar[!grepl(".*\\..*", rta$datevar)], ".00")
rta
## datevar
## 1 2008-12-30 10.15
## 2 2008-12-15 23.00
## 3 2008-12-15 18.15
## 4 2008-12-26 17.00
## 5 2008-12-21 14.45
## 6 2008-12-19 23.00
# Convert the datevar to POSIXct class.
rta$datevar <- as.POSIXct(rta$datevar, format = "%Y-%m-%d %H.%M")
rta
## datevar
## 1 2008-12-30 10:15:00
## 2 2008-12-15 23:00:00
## 3 2008-12-15 18:15:00
## 4 2008-12-26 17:00:00
## 5 2008-12-21 14:45:00
## 6 2008-12-19 23:00:00