首先 - 很抱歉这么长的帖子。我想要具体!谢谢你阅读:) 我有两个向量如下:
popd = vector(mode='numeric', 100)
popr = vector(mode='numeric', 100)
这些代表2个群体中的初始分布。 我想定义这些例如。
popd[]=0.01
popr[]=0.01
我还定义了e = 0.05,然后群体将根据以下for循环进行变换:
loop <- for(i in 1:100)
{π <- function(S)
{x <- sum(popd[1:S])
return((100-S)*x)}
µ <- function(A)
{share <- vector(mode='numeric', (101-A))
share[] = A:100
return(share%*%popr[A:100])}
for(S in 1:100){vectorπ <- vector(mode='numeric', 100)
vectorπ[S]=π(S)}
for(A in 1:100){vectorµ <- vector(mode='numeric', 100)
vectorµ[A]=µ(A)}
av.payoffd <- sum(popd * vectorπ)
av.payoffr <- sum(popr * vectorµ)
newd <- vector(mode='numeric', 100)
for(S in 1:100){newd[S]=(popd[S]/(av.payoffd))}
newr <- vector(mode='numeric', 100)
for(A in 1:100){newr[A]=(popr[A]/(av.payoffr))}
newpopd <- vectorπ * newd
test1[i,2]=(sum(newpopd * (1:100)))
newpopr <- vectorµ * newr
test1[i,4]=(sum(newpopr * (1:100)))
mutationmatrix <- function(e)
{mut <- c(e, 1-(2*e), e)
return(matrix(c(1-e, e, (rep(c(rep098, mut), times=98)), rep098, e, 1-e), nrow=100))}
mutpopd <- function(e)
{mutationmatrix(e) %*% newpopd}
test1[i,3]=(sum(mutpopd(e) * (1:100)))
mutpopr <- function(e)
{mutationmatrix(e) %*% newpopr}
test1[i,5]=(sum(mutpopr(e) * (1:100)))
if(i<100){
popd=mutpopd(e)
popr=mutpopr(e)
}
if(i==100){
for(i in 1:100){
popdistcomp1[i,3]=mutpopd(e)[i,1]
popdistcomp1[i,6]=mutpopr(e)[i,1]}
}
}
test1和popdistcomp1都是我已定义的矩阵。 但是,当我要求得到结果时:
test1
i meanoffer meanmutoffer meanminaccept meanmutminaccept
[1,] 1 NaN NaN 100 99.95
[2,] 2 NaN NaN 100 99.95
[3,] 3 NaN NaN 100 99.95
[4,] 4 NaN NaN 100 99.95
[5,] 5 NaN NaN 100 99.95
[6,] 6 NaN NaN 100 99.95
[7,] 7 NaN NaN 100 99.95
[8,] 8 NaN NaN 100 99.95
[9,] 9 NaN NaN 100 99.95
[10,] 10 NaN NaN 100 99.95
和
popdistcomp1
p(i) initialpopd mutatedpopd q(a) initialpopr mutatedpopr
[1,] "p1" "0.01" "NaN" "q1" "0.01" "0"
[2,] "p2" "0.01" "NaN" "q2" "0.01" "0"
[3,] "p3" "0.01" "NaN" "q3" "0.01" "0"
[4,] "p4" "0.01" "NaN" "q4" "0.01" "0"
[5,] "p5" "0.01" "NaN" "q5" "0.01" "0"
[6,] "p6" "0.01" "NaN" "q6" "0.01" "0"
[7,] "p7" "0.01" "NaN" "q7" "0.01" "0"
[8,] "p8" "0.01" "NaN" "q8" "0.01" "0"
[9,] "p9" "0.01" "NaN" "q9" "0.01" "0"
[10,] "p10" "0.01" "NaN" "q10" "0.01" "0"
我只是为了空间而展示了前10个条目,但它们仍以相同的方式继续,但我可能会说mutatedpopr下的popdistcomp1的最后两个条目是0.05和0.95。
我不确定“NaN”条目的来源。我想代码中的代码存在问题,或者可能是我的循环结构存在问题。我是一个完全的初学者,使用R大约5天,如果我愚蠢的话,请道歉。
感谢您的帮助,
露
答案 0 :(得分:0)
一些建议:
R
高度矢量化,因此避免编写大量的“微功能”。首先,你很幸运,popd
之类的对象碰巧对函数可见(因为你没有将它们传递给函数)。请尝试使用my.pi <- sum(popd[1:S]*(100-S)
。
for
未返回值,因此请勿键入foo<-for(....
。
不要使用希腊符号。它没有帮助,很可能无法转移到其他系统。
最后,做一些调试工作。查看计算meanoffer
之前的所有计算,即test1[,4]
,检查每个步骤的输出,并查看NaN
首次出现的位置。您的步骤非常简单,因此错误应该很容易弹出。