将日期连接到单个列

时间:2017-04-09 10:20:49

标签: r date posixlt

我在Submitted.on列中的日期具有不同的格式,因此需要单独转换各种格式,然后使用ifelseas.Date将它们连接到新列中。但是,当我使用strptime将时间戳也放在新列中时,它会抛出错误和警告消息。

data$Submitted.on[0:5]
#[1] 02-06-02 0:00       03/30/2010 23:15:12 
#[3] 11-05-09 6:28       07/29/2009 23:07:38 
#[5] 07-10-05 0:00

vec1 = as.character(strptime(data$Submitted.on, "%m/%d/%Y %H:%M:%S"))
vec1[0:5]
#[1] NA                    "2010-03-30 23:15:12"
#[3] NA                    "2009-07-29 23:07:38"
#[5] NA     

vec2 = as.character(strptime(data$Submitted.on, "%m-%d-%y %H:%M"))
vec2[0:5]
#[1] "2002-02-06 00:00:00"  NA                   
#[3] "2009-11-05 06:28:00"  NA                   
#[5] "2005-07-10 00:00:00"

data['new_format']=as.Date(ifelse(is.na(vec1),vec2,vec1))

data[0:5,'new_format']

#[1] "2002-02-06" "2010-03-30" "2009-11-05" "2009-07-29"
#[5] "2005-07-10"

使用as.Date效果很好但是当我使用strptime作为时间戳时,它会发出警告信息。

data['new_format']=strptime(ifelse(is.na(vec1),vec2,vec1),"%Y-%m-%d 
%H:%M:%S")

#Warning message:
#In `[<-.data.frame`(`*tmp*`, "new_format", value = list(sec = c(0,  :
#provided 11 variables to replace 1 variables

data[0:5,'new_format']
[1]  0 12  0 38  0

任何有关如何获得时间戳的帮助也会有很大的帮助。

1 个答案:

答案 0 :(得分:1)

我们可以使用parse_date_time

中的lubridate
library(lubridate)
parse_date_time(data$Submitted.on, guess_formats(data$Submitted.on, 
       c("mdy HMS", "mdy MS")))
#[1] "2002-02-06 00:00:00 UTC" "2010-03-30 23:15:12 UTC" "2009-11-05 00:06:28 UTC" 
#[4] "2009-07-29 23:07:38 UTC" "2005-07-10 00:00:00 UTC"

关于ifelse的使用,我们会提倡反对这一点,因为strptime会提供POSIXlt类。因此,可以使用索引方法

代替ifelse
v1 <- strptime(data$Submitted.on, "%m/%d/%Y %H:%M:%S", tz = "UTC")
v1[is.na(v1)] <- strptime(data$Submitted.on[is.na(v1)], "%m-%d-%y %H:%M", tz = "UTC")
v1
#[1] "2002-02-06 00:00:00 UTC" "2010-03-30 23:15:12 UTC" "2009-11-05 06:28:00 UTC"
#[4] "2009-07-29 23:07:38 UTC" "2005-07-10 00:00:00 UTC"

数据

data <- structure(list(Submitted.on = c("02-06-02 0:00", "03/30/2010 23:15:12", 
"11-05-09 6:28", "07/29/2009 23:07:38", "07-10-05 0:00")),
 .Names = "Submitted.on", row.names = c(NA, -5L), class = "data.frame")