Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I vectorise a function?

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 ifs.

like image 988
sds Avatar asked Sep 12 '13 14:09

sds


2 Answers

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"
like image 129
Josh O'Brien Avatar answered Oct 06 '22 08:10

Josh O'Brien


The easiest way to do something like this with zero thought is to just use Vectorize

difftime2stringVect <- Vectorize(difftime2string)
like image 29
Dason Avatar answered Oct 06 '22 09:10

Dason