【问题标题】:Run a pop-gen simulation several times and store the results of each in a new column on a data frame多次运行 pop-gen 模拟,并将每次的结果存储在数据框的新列中
【发布时间】: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


    【解决方案1】:

    这里有很多改进的机会,但这应该会让你继续前进。我只展示了五个模拟,但你应该能够扩展。本质上,将大部分代码放在一个函数中,然后您可以使用 purrr 包中的 map 函数,或者您也可以使用 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 (v0.2.1) 于 2019 年 3 月 21 日创建

    注意:您还可以为 xy(即 run_sim &lt;- function(x, y) { ... })向 run_sim 函数添加参数,这将允许您探索其他可能性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 2023-03-29
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多