How do I vectorize this function?
difftime2string <- function (x) {
if (abs(x) < 1) return(sprintf("%.2fms",x*1000))
if (abs(x) < 100) return(sprintf("%.2fsec",x))
if (abs(x) < 6000) return(sprintf("%.2fmin",x/60))
if (abs(x) < 108000) return(sprintf("%.2fhrs",x/3600))
if (abs(x) < 400*24*3600) return(sprintf("%.2fdays",x/(24*3600)))
sprintf("%.2fyears",x/(365.25*24*3600))
}
EDIT: I mean without Vectorize
- how do I write vectorised code with many if
s.
difftime2string <- function(x) {
breaks <- c(0, 1, 100, 6000, 108000, 400*24*3600, Inf)
units <- c("ms", "sec", "min", "hrs", "days", "years")
fact <- c(1000, 1, 1/60, 1/3600, 1/(24*3600), 1/(365.25*24*3600))
ii <- findInterval(x, breaks)
sprintf(paste0("%.2f", units[ii]), x*fact[ii])
}
x <- c(.1, 2, 200, 6001, 109000, 500*24*3600)
difftime2string(x)
# [1] "100.00ms" "2.00sec" "3.33min" "1.67hrs" "1.26days" "1.37years"
The easiest way to do something like this with zero thought is to just use Vectorize
difftime2stringVect <- Vectorize(difftime2string)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With