这是数据框:
> input
start end date
1 10:01 AM 10:20 AM 3/10/2014
2 8:30 PM 8:31 PM 3/10/2014
3 8:36 PM 8:45 PM 3/10/2014
4 9:30 PM 9:40 PM 3/10/2014
5 8:34 PM 3/11/2014 8:40 PM 3/11/2014 3/10/2014
6 9:02 PM 3/11/2014 9:40 PM 3/11/2014 3/10/2014
7 10:35 PM 3/11/2014 10:40 PM 3/11/2014 3/10/2014
8 11:34 PM 3/11/2014 11:40 PM 3/11/2014 3/10/2014
对于专栏#34;开始"和"结束"让日期不仅仅是时间,所以任何人都知道我如何只用时间来取代那些字段,用时间和日期(开始或结束日期)替换它,如下所示:
> input
start end date
1 10:01 AM 3/10/2014 10:20 AM 3/10/2014 3/10/2014
2 8:30 PM 3/10/2014 8:31 PM 3/10/2014 3/10/2014
3 8:36 PM 3/10/2014 8:45 PM 3/10/2014 3/10/2014
4 9:30 PM 3/10/2014 9:40 PM 3/10/2014 3/10/2014
5 8:34 PM 3/11/2014 8:40 PM 3/11/2014 3/10/2014
6 9:02 PM 3/11/2014 9:40 PM 3/11/2014 3/10/2014
7 10:35 PM 3/11/2014 10:40 PM 3/11/2014 3/10/2014
8 11:34 PM 3/11/2014 11:40 PM 3/11/2014 3/10/2014
答案 0 :(得分:0)
不太确定从哪里获取日期...例如,第8行中的日期与第8行中的开始或结束时间不匹配...但是这可能会有所帮助。
a <- "15:05"
b <- "1-1-2014"
as.Date(paste(a,b), format="%H:%M %m-%d-%Y")
[1] "2014-01-01"
答案 1 :(得分:0)
可能有一种更简洁的方法可以做到这一点,但它应该完成工作:
input <- data.frame(
start=c(
"10:01 AM","8:30 PM",
"8:34 PM 3/11/2014",
"9:02 PM 3/11/2014"),
end=c(
"10:20 AM","8:31 PM",
"8:40 PM 3/11/2014",
"9:40 PM 3/11/2014"),
date=rep("3/10/2014",4),
stringsAsFactors=FALSE)
##
## trim any whitespace
input$start <- gsub("^\\s+|\\s+$","",input$start)
input$end <- gsub("^\\s+|\\s+$","",input$end)
## rows where 'start' is malformed
sIdx <- !grepl("(.+)(\\d+\\/\\d+\\/\\d+)",input$start)
input[sIdx,"start"] <- paste0(
input$start[sIdx]," ", input$date[sIdx])
## rows where 'end' is malformed
eIdx <- !grepl("(.+)(\\d+\\/\\d+\\/\\d+)",input$end)
input[eIdx,"end"] <- paste0(
input$end[eIdx]," ", input$date[eIdx])
##
> input
start end date
1 10:01 AM 3/10/2014 10:20 AM 3/10/2014 3/10/2014
2 8:30 PM 3/10/2014 8:31 PM 3/10/2014 3/10/2014
3 8:34 PM 3/11/2014 8:40 PM 3/11/2014 3/10/2014
4 9:02 PM 3/11/2014 9:40 PM 3/11/2014 3/10/2014