r 中的复杂日期操作

Complex dates manipulation in r

我有一个包含两列的 data.frame。两者,日期为字符:

a <- c("01-01-2007 00:00:00", "01-02-2007 00:00:00", "03-05-2007 00:00:00", "31-08-2007 00:00:00")
b <- c("01-01-1960 01:25:30", "01-01-1960 1:05:36", "01-01-1960 02:25:59", "01-01-1960 1:20:30")
df <- as.data.frame(cbind(a,b))
df
                    a                   b
1 01-01-2007 00:00:00 01-01-1960 01:25:30
2 01-02-2007 00:00:00  01-01-1960 1:05:36
3 03-05-2007 00:00:00 01-01-1960 02:25:59
4 31-08-2007 00:00:00  01-01-1960 1:20:30

第一列有我需要的日期,但时间不正确。第二列中的时间是正确的,但日期不是。第二列也有问题,在某些行中,小时数只有一个数字。

我需要的是以我可以用来按时间表示计数频率的时间格式合并两列。

我尝试了很多不同的组合来合并两列,但总是出错。 as.Date()别耽误我时间,data.frame申请不了as.POSIXct

非常感谢您的帮助。

谢谢

尝试使用 lubridate 包:

library(lubridate)

a <- c("01-01-2007 00:00:00", "01-02-2007 00:00:00", "03-05-2007 00:00:00", "31-08-2007 00:00:00")
b <- c("01-01-1960 01:25:30", "01-01-1960 1:05:36", "01-01-1960 02:25:59", "01-01-1960 1:20:30")
df <- as.data.frame(cbind(a,b))
df

hr <- hour(parse_date_time(b, "dmy HMS"))
minu <- minute(parse_date_time(b, "dmy HMS"))
sec<- second(parse_date_time(b, "dmy HMS"))

getDate <- as_date(parse_date_time(a, "dmy HMS"))
getTime <- paste(hr, minu, sec, sep = ":")

as_datetime(paste(getDate, getTime))

使用基本函数,我们可以这样做:

a = as.POSIXct(a, '%d-%m-%Y %H:%M:%S', tz = "GMT")
b = as.POSIXct(b, '%d-%m-%Y %H:%M:%S', tz = "GMT")
df <- data.frame(a,b)
df$merged = paste(strftime(df$a, '%d-%m-%Y', tz = "GMT"), strftime(df$b, '%H:%M:%S', tz = "GMT"))
df

# 
#            a                   b              merged
# 1 2007-01-01 1960-01-01 01:25:30 01-01-2007 01:25:30
# 2 2007-02-01 1960-01-01 01:05:36 01-02-2007 01:05:36
# 3 2007-05-03 1960-01-01 02:25:59 03-05-2007 02:25:59
# 4 2007-08-31 1960-01-01 01:20:30 31-08-2007 01:20:30

使用 regex 将正确的部分放在一起(假设中间有 space):

df$good_string = paste(gsub(pattern = " .*", "", x = df$a), gsub(pattern = ".* ", "", df$b), sep = " ")
df$parsed_date = as.POSIXct(df$good_string, format = "%d-%m-%Y %H:%M:%S")
df[3:4]
#           good_string         parsed_date
# 1 01-01-2007 01:25:30 2007-01-01 01:25:30
# 2  01-02-2007 1:05:36 2007-02-01 01:05:36
# 3 03-05-2007 02:25:59 2007-05-03 02:25:59
# 4  31-08-2007 1:20:30 2007-08-31 01:20:30