FredH - 9 months ago 52

R Question

Here I have written a code that uses the geometrical function rgeom() to check if something was successful on the first try. However, I can't get it to say how many times it took, when it has to be successful on the first try.

Thats the reason i assign A & B to get its values from k. When k has been reached, it was supposed to print out how many times it took, but now it only prints out k+1.

`test <- function(k){`

p <- 1/3

trials <- 1

A <- k

B <- k

for(i in 1:1000){

while(B > 0){

if (rgeom(1, p) == 0){

B = B-1

trials = trials +1

break

}else {

A = A-1

break

}

}

}

print(trials)

}

Answer

Try this:

```
p <- 1/3 # parameter of the geometric variable
n <- 1000 # number of trials
sum(replicate(n, {rgeom(1,p)})==1) # number of times it was successful on the first try
```

Source (Stackoverflow)