Paste Date to Time in an Irregular Way

366 Views Asked by At

I am trying to combine times with it's corresponding date, but am having trouble. The dates and times are in one list where the date is followed by times for that date. This papptern continues in an irregular fashion.

Here's what I tried so far:

z = as.data.frame(c("2014-12-01", "7:00", "8:00", "9:00"))
z$x = llply(z[[1]], as.Date, format = "%Y-%m-%d")
names(z) = c("a", "b")
dp = function (x) {x = z$b
                  if(class(x) != "Date") {paste(z$a, x)} else {x = z$b}}
as.data.frame(llply(z, dp))[1]

And I get:

             a
1 2014-12-01 16405
2          7:00 NA
3          8:00 NA
4          9:00 NA

I'm looking for:

             a
1 2014-12-01
2          7:00 2014-12-01
3          8:00 2014-12-01
4          9:00 2014-12-01

Ideally, i'd like a solution to combine the date and time into a single date-time object.

Please help...thanks

1

There are 1 best solutions below

0
On BEST ANSWER

If you need a date-time object

library(data.table)
setDT(df)[, as.POSIXct(paste(v1[1], v1[-1]), format='%Y-%m-%d %H:%M'), by=gr]
#    gr                  V1
#1:  1 2014-12-01 07:00:00
#2:  1 2014-12-01 08:00:00
#3:  1 2014-12-01 09:00:00
#4:  2 2014-12-02 06:00:00
#5:  2 2014-12-02 09:00:00

Or if you need it to be in the format as shown in the result

 setDT(df)[, c(v1[1],paste(v1[-1], v1[1])) , by=gr]
 #   gr              V1
 #1:  1      2014-12-01
 #2:  1 7:00 2014-12-01
 #3:  1 8:00 2014-12-01
 #4:  1 9:00 2014-12-01
 #5:  2      2014-12-02
 #6:  2 6:00 2014-12-02
 #7:  2 9:00 2014-12-02

data

v1 <- c("2014-12-01", "7:00", "8:00", "9:00", "2014-12-02", "6:00", "9:00")
indx <- grepl('-', v1)
df <- data.frame(v1, gr=cumsum(indx), stringsAsFactors=FALSE)