mardi 15 juin 2021

Time Conditional Formatting in R from 24hr to 12hr time

Sample Data:

Time Temperature
11:50 76
14:46 76
15:00 75

I want to convert the times from 24hr to 12hr format. Instead of 11:50 I would like it to say 11:50 AM and instead of 15:00 I would like it to say 3:00 PM.

So far I tried to make 2 new columns just for use in calculations. Hour has just the first 2 numbers of the time (aka the hour).

df$Hour <- as.numeric(substr(df$Time, start = 12, stop = 13))

Time take the full 4 digit time.

df$Time <- substr(df$Time, start = 12, stop = 16)

I know I have to loop through the times and classify those with an hour less than 13 as "AM" and everything else as "PM". Eventually I'll need to convert the actual numbers from 13 back to 12hr format as 1 PM but that's for later. Right now, I am having issues with just the loop. This piece of code will correctly print all the times that are less than 12 (AM times) but for some reason I can't get it to actually update the new_time column in the right time. All of them say PM. I think I am placing it in the wrong spot or something.

for (i in df$Hour) {
  if (i > 12) {
    print(paste(i, "is > 12"))
      df$new_time <- paste(df$Time, AMPM)
    }
}

OUTPUT:

[1] "14 is > 12"
[1] "15 is > 12"

OUTPUT TABLE:

Time Temperature new_time
11:50 76 11:50 PM
14:46 76 14:46 PM
15:00 75 15:00 PM

Aucun commentaire:

Enregistrer un commentaire