I am currently working with RStudio for the first time and have a problem with the following task:
2 n people go to vote for the mayor, exactly n people vote for one of the two candidates. Use a simulation to approximate the probability of the following event: At no point during the count is the difference in votes between the two candidates greater than 2. Experiment with different values for n, for example 2,5,10 and 50 .
The following code is given:
#Vorbereitende Befehle
n <- 10
x <- sample(c(rep(1,n),rep(-1,n)),size=2*n) #Simulation des Auszaehlens
x
cumsum(x) #alle Partialsummen
min(cumsum(x))
#Lösen der Problemstellungen durch R=1000 (oder mehr) Durchlaeufe
R <- 10000 #R Wiederholungen
erg <- rep(0,R) #Abspeichern ob Bedingung erfuellt oder nicht
n <- 1000
for(i in 1:R){
x <- sample(c(rep(1,n),rep(-1,n)),size=2*n)
if(min(cumsum(x))>=0){erg[i] <- 1} #falls Bedingung erfüllt kommt 1 in Vektor
}
mean(erg) #Prozentsatz (=Schaetzung fuer Wahrscheinlichkeit)
In the script, the result for 2 is approx. 0.09 and for 50 approx. 0.0196 - I always get different results even with the same n?
I think there's something fundamental about the way Rstudio works that I haven't understood yet - but I can't figure it out!