implicit return? [R for BE/BA]

posted by ElMaestro  – Belgium?, 2019-04-29 10:55 (540 d 17:20 ago) – Posting: # 20262
Views: 4,213

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

I could be wrong, but...

Best regards,
ElMaestro

R's base package has 274 reserved words and operators, along with 1761 functions. I can use 18 of them (about 14 of them properly). I believe this makes me the Donald Trump of programming.

Complete thread:

Activity
 Admin contact
21,170 posts in 4,411 threads, 1,474 registered users;
online 4 (0 registered, 4 guests [including 3 identified bots]).
Forum time: Wednesday 04:15 UTC (Europe/Vienna)

But it is in matters beyond the limits of mere rule
that the skill of the analyst is evinced.
He makes in silence a host of observations and inferences…    Edgar Allan Poe

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