[R] simple simulation problem

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sun Mar 17 22:58:45 CET 2002

Yannick Wurm <idh at poulet.org> writes:

> Help!
> I'm desperate! I don't understand why my function won't work!
> Its for a simple simulation exercise: robin hood fires an arrow at a
> target with 50cm radius, and his aim follows a centered normal
> distribution with a standard deviation of 40cm (on x and y axis,
> independently). Here he takes 10 shots and is awarded points if he
> hits close to the center.
> For some reason, this function always returns a score of 870?!?!
> I'm probably missing something really quite obvious but I just can't
> figure out what it is.

> 	if (40 < d[i] < 50) score_sum(score,2)

That doesn't work (in R as well as most other programming languages).
It gets evaluated left to right as either TRUE < 50 or FALSE < 50,
both of which will be TRUE since logicals coerce to 0 or 1. You must
split it as (40 < d[i] && d[i] < 50).

(The whole thing can be coded much more elegantly with cut() and
indexing, but you'll probably learn soon enough.)

BTW: "_" as assignment is hard to read, and likely to get removed in
future versions of R so you might as well break the habit now.

   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list