Created
August 11, 2016 16:12
-
-
Save kbroman/657728ea68171bac0414ddd223791e1f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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