-2

i'm a beginner in R. I bet this question sounds stupid but its so specific i cannot find information in the internet. I have to calculate process times from a data frame. The problem is, the dataframe has a col of dates and a col of times. Is there an easy possibility for me to merge them to get a time stamp without using loops?

dww
  • 30,425
  • 5
  • 68
  • 111
Ernsthaft
  • 177
  • 1
  • 1
  • 9

1 Answers1

1

Consider this data example:

df <- data.frame(day = as.Date(c("2018-07-25", "2018-07-24")),
                 times = c("05:24:36", "11:27:14"))

         day    times
1 2018-07-25 05:24:36
2 2018-07-24 11:27:14

Now use paste in combination with as.POSIXct to create a timestamp variable with a vectorized operation.

df$ts <- as.POSIXct(paste(df$day, df$times, sep = " "))

         day    times                  ts
1 2018-07-25 05:24:36 2018-07-25 05:24:36
2 2018-07-24 11:27:14 2018-07-24 11:27:14
LAP
  • 6,605
  • 2
  • 15
  • 28
  • 1
    Perhaps add the usage to define the format, if the dates and times are not in the standard or not yet stored in the correct datatype. `df$ts <- as.POSIXct(paste(df$day, df$times, sep = " "), tryFormats = c("%Y-%m-%d %H:%M:%OS"))` – hannes101 Jul 25 '18 at 08:25
  • Thank you. I tried a bit around with this solution. It should work for me! – Ernsthaft Jul 25 '18 at 08:27
  • 2
    `paste` by default has `sep = " "` – Ronak Shah Jul 25 '18 at 08:34