1

My R code:

bnc1<-function(maxITR=100000, d=2, l=1){
    counts=0;
    for (i in 1:maxITR){
        x=runif(1,0,pi);
        y=runif(2,0,d/2);
        if ((l/2*sin(x)) >= y) counts=counts+1;
    } 
    counts/maxITR*d/l
}

Running the code:

> bnc1(maxITR=1000)
[1] 0.652
There were 50 or more warnings (use warnings() to see the first 50)
> warnings()
Warning messages:
1: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used
2: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used
...
49: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used
50: In if ((l/2 * sin(x)) >= y) counts = counts + 1 ... :
  the condition has length > 1 and only the first element will be used

Does anyone has an idea what causes the warnings?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
Tim
  • 1
  • 141
  • 372
  • 590

1 Answers1

6

runif returns a vector.

if takes a single value (not a vector).

Check the manual for runif, I don't think you are using it right.


In R, it often makes sense to remove for loops and use vectors instead - for example:

bnc1<-function(maxITR=100000, d=2, l=1){
    x=runif(maxITR,0,pi);
    y=runif(maxITR,0,d/2);
    counts = sum((l/2*sin(x)) >= y);
    counts/maxITR*d/l
}
Alex Brown
  • 41,819
  • 10
  • 94
  • 108
  • okay, sounds like you have a fix. You may find my example is a useful simplification. – Alex Brown Dec 06 '10 at 14:12
  • 1
    @Tim : every time you use `if`, ask yourself if that really is necessary. So many programmers coming from a non-vectorized language forget that the most powerful trick in R is the vectorization of the vast majority of the functions. – Joris Meys Dec 06 '10 at 14:16
  • 3
    And each time you use 'for', don't use for. – Alex Brown Dec 06 '10 at 14:18
  • @Joris and Alex: Thanks for all your advice. – Tim Dec 06 '10 at 14:21
  • @Alex Brown: your comment on `for` is bogus! There is nothing wrong with using a `for` loop in R and I would advise it's use in many cases where an `apply` or similar might also be used. Why? Code readability and legibility of a `for` is often more important than getting a succinct 1-liner. If often see people who've been told never to use `for` loops trying to force their code into a custom function to use with `apply` when a simple loop would have been easier to code, and easier to read. – Gavin Simpson Dec 06 '10 at 16:42
  • can you give an example? For me, writing 'custom functions' is how you USE R - it's not a silly trick. – Alex Brown Dec 06 '10 at 17:05