【发布时间】:2019-03-21 18:50:58
【问题描述】:
我对两个等位基因进行了基本的 Wright-Fisher 模拟,效果非常好,并生成了一个好看的图,显示等位基因按预期固定或偶然消失。它将每一代的计算结果导出到数据框 d 中,因此我掌握了每一代的值。我想要做的是运行整个事情说 20 次,并自动将每个完整的模拟存储在一个新列中,这样我就可以将它们全部绘制在带有颜色和所有好东西的 ggplot 图上。我最感兴趣的是获得一个整洁的框架来为项目制作好看的情节,而不是极好的效率。
#Wright Fisher model Mk1
#Simulation Parameters
# n = pop.size
# f = frequency of focal allele
# x = number of focal allele, do not set by hand
# y = number of the other allele, do not set by hand
# g = generations desired
n = 200
f = 0.6
x = (n*f)
y = (n-x)
g = 200
#This creates a data frame of the correct size to store each generation
d = data.frame(f = rep(0,g))
#Creates the graph.
plot(1,0, type = "n", xlim = c(1,200), ylim = c(0,n),
xlab = "Generation", ylab = "Frequency A")
#Creates the population, this model is limited to only two alleles, and can only plot one
alleles<- c(rep("A",x), rep("a",y))
#this is the loop that actually simulates the population
#It has code for plotting each generation on the graph as a point
#Exports the number of focal allele A to the data frame
for (i in 1:g){
alleles <- sample(alleles, n, replace = TRUE)
points(i, length(alleles[alleles=="A"]), pch = 19, col= "red")
F = sum(alleles == "A")
d[i, ] = c(F)
}
所以我想多次运行最后一点并以某种方式存储每个完整的迭代。我知道我可以通过嵌套来循环该函数,尽管这既快又脏,但这样做只会存储外循环最后一次迭代的值。
【问题讨论】:
标签: r loops dataframe nested-loops