implicit return? [🇷 for BE/BA]

posted by ElMaestro  – Denmark, 2019-04-29 14:55 (1822 d 13:37 ago) – Posting: # 20262
Views: 6,579

Hi Hötzi,

❝ Use ifelse() for vectorized conditions. See this thread.


Try this:
library(microbenchmark)

x=round(runif(100),0)
Len=100

f1=function(x, Len)
{
 ifelse ((x==0), "foo", "bar")
}

f1(x, Len)


f2=function(x, Len)
{
 rslt=rep("foo", Len)
 for (i in 1:Len)
  if (x[i]) rslt[i]="bar"
 return(rslt)
}

f2(x, Len)



res <- microbenchmark(
                      f1(round(runif(Len),0), Len),
                      f2(round(runif(Len),0), Len),
                      times=3000L)
print(res)


note I am passing Len to f1 even though it is not used there in order to give the function call the same overhead, otherwise the comparison might be called unfair.

On my system f2 is a lot faster, so the advantage of runif may be solely syntactic and not in any way a true vectorisation advantage (easier but not more efficient).

Pass or fail!
ElMaestro

Complete thread:

UA Flag
Activity
 Admin contact
22,993 posts in 4,828 threads, 1,657 registered users;
119 visitors (0 registered, 119 guests [including 4 identified bots]).
Forum time: 04:32 CEST (Europe/Vienna)

Never never never never use Excel.
Not even for calculation of arithmetic means.    Martin Wolfsegger

The Bioequivalence and Bioavailability Forum is hosted by
BEBAC Ing. Helmut Schütz
HTML5