I’m trying to write RPS game. Below is my code. Running it in Rstudio nothing happens but in basic R i get an evaluation error in line 29, “missing value where true/false needed” and also the plots get errors for unequal x,y axis. There must be something simple i’m missing as to why only that if is wrong. Thanks for your time.
Np<-1200 #pop size
Ng<-300 #generation time
P<-matrix(data=NA, nrow=Np/2, ncol=2) #matrix of pop
strategy=c('Ro','Pa','Sc')
P1<-sample(strategy, size=Np, replace=TRUE, prob=c(1/3,1/3,1/3)) #pop with equal probs of any strategy
# "res <- matrix(P1, nrow=Ng, ncol=3) #matrix for results" # defunct remove!
fR=c()
fP=c()
fS=c()
# result vectors for each strategy
# res<-matrix(NA, ng,3) # matrix as per example. results vectors returned null.
pR<- 0.5
pP<- 0.5
pS<- 0.5
# probabilities of success in each encounter of pX winning.
for(i in 1:Ng) {
for(j in 1:(Np/2)){
if(P[j,1]=='Ra'& P[j,2]=="Sc"& runif(1)<pR){P[j,2]<-"Ra"
}
if(P[j,1]=='Pa'& P[j,2]=="Sc"& runif(1)<pS){P[j,1]<-"Sc"
}
if(P[j,1]=='Sc'& P[j,2]=="Ra"& runif(1)<pR){P[j,1]<-"Ra"
}
if(P[j,1]=='Ra'& P[j,2]=="Pa"& runif(1)<pP){P[j,1]<-"Pa"
}
if(P[j,1]=='Pa'& P[j,2]=="Ra"& runif(1)<pP){P[j,2]<-"Pa"
}
if(P[j,1]=='Sc'& P[j,2]=="Pa"& runif(1)<pS){P[j,2]<-"Sc"
}
} # each row fights and winner replaces with appropriate probability.
P[,2]<-sample(P[,2]) #randomise interactions
fR=c(fR, sum(P=="Ra"))
fP=c(fP, sum(P=="Pa"))
fS=c(fS, sum(P=="Sc"))
}
plot(x=fR,y=Ng, ylab="frequency", xlab="Generation", col="black", type="l")
lines(fP, Ng, col="green")
lines(fS, Ng, col="red")
It errors out when
ianjare 1. (Unlike other functions, the for-loop indices remain in their last assignment if a loop terminates abnormally.) You cannot test with “==” when yourPmatrix is all NA. Theiffunction raises an error when the test returnsNA. Maybe you meant to write the inner loop tests withP1? Perhaps yhis will be a happier setup meta-strategy: