我有数据集,其中time.start
从5:00:00到28:59:59不等(即01.01.2013 28:00:00实际上是02.01.2013 04:00:00)。日期为%d.%m.%Y
格式。
Date Time.start
01.01.2013 22:13:07
01.01.2013 22:52:23
01.01.2013 23:34:06
01.01.2013 23:44:25
01.01.2013 27:18:48
01.01.2013 28:41:04
我想将其转换为普通日期格式。
dates$date <- paste(dates$Date,dates$Time.start, sep = " ")
dates$date <- as.POSIXct(strptime(dates$date, "%m.%d.%Y %H:%M:%S"))
但显然我有NA
时间&gt; 23时59分59秒
我应该如何修改我的代码?
答案 0 :(得分:8)
E.g。将时间添加为日期的秒数:
df <- read.table(header=T, text=" Date Time.start
01.01.2013 22:13:07
01.01.2013 22:52:23
01.01.2013 23:34:06
01.01.2013 23:44:25
01.01.2013 27:18:48
01.01.2013 28:41:04", stringsAsFactors=FALSE)
as.POSIXct(df$Date, format="%d.%m.%Y") +
sapply(strsplit(df$Time.start, ":"), function(t) {
t <- as.integer(t)
t[3] + t[2] * 60 + t[1] * 60 * 60
})
# [1] "2013-01-01 22:13:07 CET" "2013-01-01 22:52:23 CET" "2013-01-01 23:34:06 CET"
# [4] "2013-01-01 23:44:25 CET" "2013-01-02 03:18:48 CET" "2013-01-02 04:41:04 CET"
答案 1 :(得分:8)
只需修改lukeAs解决方案:
with(df, as.POSIXct(Date, format="%d.%m.%Y")+
colSums(t(read.table(text=Time.start, sep=":",header=F))*c(3600,60,1)))
[1] "2013-01-01 22:13:07 EST" "2013-01-01 22:52:23 EST"
[3] "2013-01-01 23:34:06 EST" "2013-01-01 23:44:25 EST"
[5] "2013-01-02 03:18:48 EST" "2013-01-02 04:41:04 EST"
答案 2 :(得分:2)
使用lubridate
:
with(dates, mdy(Date) + hms(Time.start))
生成:
[1] "2013-01-01 22:13:07 UTC" "2013-01-01 22:52:23 UTC"
[3] "2013-01-01 23:34:06 UTC" "2013-01-01 23:44:25 UTC"
[5] "2013-01-02 03:18:48 UTC" "2013-01-02 04:41:04 UTC"