Cardinal
Cardinal

Reputation: 228

R error number of items to replace is not a multiple of replacement length

I try to write a script that simulates 100 coin tosses with a certain probability of success, a starting capital and certain amount of capital to stop the game ('l'). It returns the probability of success. The code works, but it returns an error message. Could someone help me out? Thanks in advance!

spins=100
SuccessVector=c()
ProbSuccess<-function(p, capital, l){
for(i in 1:spins){
cap=rep(capital,spins)
while(cap[i]>0 & cap[i]<l){
cap[i]=cap[i]+sample(c(-1,1), replace = TRUE, prob= c(1-p,p))
if(cap[i]==l){SuccessVector[i]=1}
else(SuccessVector[i]=0)
}
}
successes=length(SuccessVector[SuccessVector==1])/length(SuccessVector)
return(successes)
}
ProbSuccess(0.5,10,20)

There were 50 or more warnings (use warnings() to see the first 50)

warnings()

Warning messages: 1: In cap[i] = cap[i] + sample(c(-1, 1), replace = TRUE, ... : number of items to replace is not a multiple of replacement length

Upvotes: 0

Views: 670

Answers (1)

David Heckmann
David Heckmann

Reputation: 2939

From the help of sample():

"For sample the default for size is the number of items inferred from the first argument, so that sample(x) generates a random permutation of the elements of x (or 1:x)."

That's why you get samples of size 2. You might want to use:

cap[i]=cap[i]+sample(c(-1,1), size=1 , replace = TRUE, prob= c(1-p,p))

Upvotes: 1

Related Questions