0

This loop is going over all the values of i in range(92:1000) and whichever value of i is holding the condition true it is breaking the loop by setting that value of i in c and when i am trying to run this code block in R language it is giving me c=1000.

> c=0
> for (i in range(92:1000)){
+     if(dpois(i,94.32)<=dpois(5,94.32))
+         {c=i;
+         break;
+         }
+ }
> c
[1] 1000

But what i expected it should give value of c=235 as at i=235 as:--

> dpois(235,94.32)
[1] 2.201473e-34
> dpois(5,94.32)
[1] 6.779258e-34
> dpois(235,94.32)<=dpois(5,94.32)
[1] TRUE

And it should break whenever the condition is true for the first time.

Where am i going wrong ?

  • 2
    Range does not do what you think it does, that's a python command. Use just 92:1000. – user2974951 Apr 08 '20 at 05:39
  • To determine why what @user2974951 said is the right answer, run through this step by step. Steps, out of order: (2) Assign the first value from `range(...)` into `i`; (3) `dpois(i,94.32)` and `dpois(5,94.32)`; (4) assign the next value from `range(...)` into `i`; (5) `dpois(i,94.32)` and `dpois(5,94.32)` again; but the first step should be very englightening: (1) since you expect it to be a long vector, no need to flood the console, just use `head(range(92:1000))` (or `length(range(92:1000))`) ... though you expect `92 93 94 ... 998 999 1000`, you'll only see `92 1000`, two values. – r2evans Apr 08 '20 at 05:47
  • Oh ! Thanks @user2974951 , it worked – Abhishek soni Apr 08 '20 at 05:48
  • @Abhisheksoni As an aside: better don't call your object `c` since that is a built-in function. – markus Apr 08 '20 at 06:29

1 Answers1

1

In R, range computes the range of the given data, i.e. the minimum and maximum

> range(92:1000)
[1]   92 1000

Also, using c as a variable name is very bad practice in R. Since c is an intrinsic function used to define vectors.

The following gives the expected answer

> c0=0
>  for (i in 92:1000){
+        if(dpois(i,94.32)<=dpois(5,94.32))
+              {
+          
+              c0=i
+              break
+              
+              }
+    }
> c0
[1] 234
jcken
  • 435
  • 3
  • 9
  • 2
    Of course, it would be better to do without the loop altogether, since `dpois` is vectorised. You could replace the whole thing with `c0 <- 91 + which(dpois(92:1000, 94.32) < dpois(5, 94.32))[1])` – Allan Cameron Apr 08 '20 at 07:33