rcluster-analysisanalyticsdata-analysischron

Conditionally Add 12 hours to column


Using library(chron) Here is the

df <- structure(list(Time = structure(c(0.376736111111111, 0.376666666666667, 
0.376435185185185, 0.376354166666667, 0.376319444444444, 0.376284722222222, 
0.376134259259259, 0.376122685185185, 0.376006944444444, 0.37587962962963
), format = "h:m:s", class = "times"), `am/pm` = c("am", "am", 
"am", "am", "am", "pm", "pm", "pm", "pm", "pm")), row.names = c(NA, 
10L), class = "data.frame")

I have a column for Time in Chron() "times" format (in 12 hr time) and an am/pm column.

I'd like to create a MilitaryTime column that adds 12 hours to Time if pm, and adds 0 hours to Time if am

Thanks!


Solution

  • df$Time24 = df$Time + ifelse(df$`am/pm` == "pm", 0.5, 0)
    #        Time am/pm   Time24
    # 1  09:02:30    am 09:02:30
    # 2  09:02:24    am 09:02:24
    # 3  09:02:04    am 09:02:04
    # 4  09:01:57    am 09:01:57
    # 5  09:01:54    am 09:01:54
    # 6  09:01:51    pm 21:01:51
    # 7  09:01:38    pm 21:01:38
    # 8  09:01:37    pm 21:01:37
    # 9  09:01:27    pm 21:01:27
    # 10 09:01:16    pm 21:01:16