Here I used a few years. It is also vectorized.
toSeconds <- function(x){ if (!is.character(x)) stop("x must be a character string of the form H:M:S") if (length(x)<=0)return(x) unlist( lapply(x, function(i){ i <- as.numeric(strsplit(i,':',fixed=TRUE)[[1]]) if (length(i) == 3) i[1]*3600 + i[2]*60 + i[3] else if (length(i) == 2) i[1]*60 + i[2] else if (length(i) == 1) i[1] } ) ) }
And vice versa (saves fractional seconds by the number of requested digits:
secondsToString <- function(x,digits=2){ unlist( lapply(x, function(i){ # fractional seconds fs <- as.integer(round((i - round(i))*(10^digits))) fmt <- '' if (i >= 3600) fmt <- '%H:%M:%S' else if (i >= 60) fmt <- '%M:%S' else fmt <- '%OS' i <- format(as.POSIXct(strptime("0:0:0","%H:%M:%S")) + i, format=fmt) if (fs > 0) sub('[0]+$','',paste(i,fs,sep='.')) else i } ) ) }
Jeff
source share