0

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

jdesilvio
  • 1,794
  • 4
  • 22
  • 38
  • The desired result still looks like `character` column instead of `date time`. Also, why you have `row 1` with only `date`? Is it some kind of identifier? – akrun Dec 05 '14 at 04:47
  • Another doubt is whether the time always follow the dates? – akrun Dec 05 '14 at 04:50

1 Answers1

1

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)
akrun
  • 874,273
  • 37
  • 540
  • 662