我有一个基本的赖特 - 费舍尔模拟两个等位基因的工作非常好,并产生一个好看的情节显示等位基因按预期固定或消失。它将计算出来的每一代导出到数据帧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)
}
所以我想多次运行最后一位并以某种方式存储每个完整的迭代。我知道我可以通过嵌套来循环该函数,即使这很快且很脏,但这样做只会存储外循环的最后一次迭代的值。
这里有很多改进的机会,但这应该让你前进。我只展示了五个模拟,但你应该能够扩展。本质上,将大部分代码放在一个函数中然后你可以使用map
包中的purrr
函数,或者你也可以用replicate
做一些事情:
library(tidyverse)
n = 200
f = 0.6
x = (n*f)
y = (n-x)
g = 200
d = data.frame(f = rep(0,g))
run_sim <- function() {
alleles <- c(rep("A", x), rep("a", y))
for (i in 1:g) {
alleles <- sample(alleles, n, replace = TRUE)
cnt_A = sum(alleles == "A")
d[i, ] = c(cnt_A)
}
return(d)
}
sims <- paste0("sim_", 1:5)
set.seed(4) # for reproducibility
sims %>%
map_dfc(~ run_sim()) %>%
set_names(sims) %>%
gather(simulation, results) %>%
group_by(simulation) %>%
mutate(period = row_number()) %>%
ggplot(., aes(x = period, y = results, group = simulation, color = simulation)) +
geom_line()
由reprex package创建于2019-03-21(v0.2.1)
注意:您还可以为run_sim
函数添加参数,例如x
和y
(即run_sim <- function(x, y) { ... }
),这将允许您探索其他可能性。