Skip to content

Instantly share code, notes, and snippets.

@kbroman
Created August 11, 2016 16:12
Show Gist options
  • Save kbroman/657728ea68171bac0414ddd223791e1f to your computer and use it in GitHub Desktop.
Save kbroman/657728ea68171bac0414ddd223791e1f to your computer and use it in GitHub Desktop.
# convert "5 min" "3 h" "4 d" etc to seconds
shit2sec <-
function(shit)
{
# remove leading space
shit <- sub("^\\s+", "", shit)
# remove ending space
shit <- sub("\\s+$", "", shit)
# split at white space
spl <- strsplit(shit, "\\s+")
# check that they're all length 2
nfields <- sapply(spl, length)
stopifnot(all(nfields==2))
# grab time and unit
time <- as.numeric(vapply(spl, "[", "", 1))
unit <- vapply(spl, "[", "", 2)
# first char of unit
unit <- substr(unit, 1, 1)
multiplier <- c("s"=1, "m"=60, "h"=60*60, "d"=60*60*24)
if(!all(unit %in% names(multiplier))) {
u_unit <- unique(unit)
unknown <- u_unit[!(u_unit %in% names(multiplier))]
stop("Unknown units: ", paste(unknown, collapse=" "))
}
# convert to seconds
result <- time * multiplier[unit]
names(result) <- names(shit)
result
}
# example
n <- 100
units <- sample(c("s", "sec", "hr", "hour", "mn", "min", "day", "days"), n, replace=TRUE)
times <- round(runif(n, 0, 5), 1)
input <- paste(times, units, sep=" ")
secs <- shit2sec(input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment