casanoan
casanoan

Reputation: 27

R String Padding for Times

I have a dataframe with a column representing times. However, the length of the strings are not consistent and when I try to convert them I get NAs:

Is there a way to pad the 5 character times so that all values in the column are a total of 7 characters?

times <- c("56:09", "1:05:19", "1:06:24", "1:07:22", "51:50", "57:51", "41:45", "58:25", "46:45", "58:52")

Upvotes: 0

Views: 73

Answers (2)

casanoan
casanoan

Reputation: 27

I found this also works:

times[which(nchar(times)==5)] <- paste0("00:", times[which(nchar(times)==5)])

Upvotes: 0

akrun
akrun

Reputation: 887058

Create a condition with nchar in ifelse and convert to Time using as.ITime from data.table

library(data.table)
as.ITime(ifelse(nchar(times) < 7, paste0("0:", times), times))
#[1] "00:56:09" "01:05:19" "01:06:24" "01:07:22" "00:51:50" "00:57:51" "00:41:45" "00:58:25" "00:46:45" "00:58:52"

Upvotes: 2

Related Questions