I have written the function below that takes a non-standard time format e.g. '730' (7:30) and converts it to a decimal number of hours e.g. '7.5'.
decimal_time <- function(x) {
x <- as.character(x)
tmp <- nchar(x)
if (tmp < 4 & !is.na(tmp)){
x <- paste0(strrep('0',4-tmp),as.character(x))
}
x <- sub("([[:digit:]]{2,2})$", ":\\1", x)
x <- strsplit(x,':')[[1]]
x <- as.numeric(x)
x[1]+x[2]/60
}
To apply it to one column I do the following...
dt_times[, New_Time := lapply(Time, decimal_time)]
However I can't figure out how to apply this same function to many columns that share the same format. Of course, if it was a vectorised function (like 'mean') then I could just write...
dt_times[, lapply(.SD, mean), .SDcols = c('col1', 'col2')]
... but what do I do if my function uses lapply in the first place?! Help please!
dt_times[, c('col1', 'col2') := lapply(.SD, decimal_time), .SDcols = c('col1', 'col2')]? - Jaap