0

I have a table in R like:

start                duration
02/01/2012 20:00:00  5
05/01/2012 07:00:00  6
etc...               etc...

I got to this by importing a table from Microsoft Excel that looked like this:

date        time      duration
2012/02/01  20:00:00  5
etc...

I then merged the date and time columns by running the following code:

d.f <- within(d.f, { start=format(as.POSIXct(paste(date, time)), "%m/%d/%Y %H:%M:%S") })

I want to create a third column called 'end', which will be calculated as the number of hours after the start time. I am pretty sure that my time is a POSIXct vector. I have seen how to manipulate one datetime object, but how can I do that for the entire column?

The expected result should look like:

start                duration  end
02/01/2012 20:00:00  5         02/02/2012 01:00:00
05/01/2012 07:00:00  6         05/01/2012 13:00:00
etc...               etc...    etc...
Zachary Weixelbaum
  • 904
  • 1
  • 11
  • 24
  • this question should have R code, so we know how you are referencing your data, etc. Keep in mind for your next quesiton – Liz Young Jul 01 '15 at 14:53

2 Answers2

5

Using lubridate

> library(lubridate)
> df$start <- mdy_hms(df$start)
> df$end <- df$start + hours(df$duration)
> df
#                start duration                 end
#1 2012-02-01 20:00:00        5 2012-02-02 01:00:00
#2 2012-05-01 07:00:00        6 2012-05-01 13:00:00

data

df <- structure(list(start = c("02/01/2012 20:00:00", "05/01/2012 07:00:00"
), duration = 5:6), .Names = c("start", "duration"), class = "data.frame", row.names = c(NA, 
-2L))
ExperimenteR
  • 4,453
  • 1
  • 15
  • 19
2

You can simply add dur*3600 to start column of the data frame. E.g. with one date:

start = as.POSIXct("02/01/2012 20:00:00",format="%m/%d/%Y %H:%M:%S")
start
[1] "2012-02-01 20:00:00 CST"
start + 5*3600
[1] "2012-02-02 01:00:00 CST"
Alexey Ferapontov
  • 5,029
  • 4
  • 22
  • 39