-1

我正在尝试编写 RPS 游戏。下面是我的代码。在 Rstudio 中运行它什么都没有发生,但在基本的 R 中,我在第 29 行得到一个评估错误,“需要真/假的地方缺少值”,而且绘图得到了不等 x,y 轴的错误。必须有一些简单的我想念的东西,为什么只有那个如果是错误的。谢谢你的时间。

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")
4

1 回答 1

1
Error in if (P[j, 1] == "Sc" & P[j, 2] == "Ra" & runif(1) < pR) { : 
  missing value where TRUE/FALSE needed
> i
[1] 1
> j
[1] 1
> str(P)
 logi [1:600, 1:2] NA NA NA NA NA NA ...

i当an为 1时它会出错。(与其他函数不同,如果循环异常终止,for 循环索引将保留在其最后一次赋值中。)当您的矩阵全部为 NAj时,您不能使用“==”进行测试。Pif函数在测试返回时引发错误NA。也许您打算用 ? 编写内部循环测试P1?也许 yhis 将是一个更快乐的设置元策略:

P<-matrix(data=NA, nrow=Np/2, ncol=2)   
strategy=c('Ro','Pa','Sc')
P[]<-sample(strategy, size=Np, replace=TRUE, prob=c(1/3,1/3,1/3))    
于 2013-02-18T17:29:08.693 回答