if语句-if函数中的求值错误.还绘制代码中的错误.在R中



我正在尝试编写RPS游戏。下面是我的代码。在Rstudio中运行它什么也没发生,但在基本R中,我在第29行得到了一个评估错误,"需要true/false的地方缺少值",并且绘图也得到了不相等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")
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 ...

ij为1时出错。(与其他函数不同,如果循环异常终止,for循环索引将保留在上次赋值中。)当P矩阵全部为NA时,无法使用"=="进行测试。当测试返回NA时,if函数会引发错误。也许你打算用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))    

最新更新