I'm working with a dataset with a time column in the following format:
Time
330
2230
5
45
I want to convert this to hh:mm format
Time
03:30
22:30
00:05
00:45
I'm new to R and I'm wondering if there's an easy way to do this. Any help would be appreciated.
CodePudding user response:
You can pad the time strings to 4-digit with "0"
on the left, then split the padded strins into HH:MM
.
df <- data.frame(Time = c(330, 2230, 5, 45))
# solution 1
df$Time2 <- sub("(.{2})(. )", "\\1:\\2", sprintf("d", df$Time))
# solution 2
df$Time2 <- format(strptime(sprintf("d", df$Time), "%H%M"), "%H:%M")
df
# Time Time2
# 1 330 03:30
# 2 2230 22:30
# 3 5 00:05
# 4 45 00:45