如何迭代拟合Brms回归模型并将平均值和sigma提取到数据框

时间:2019-02-11 21:56:44

标签: r function data.table tidyr rstan

鉴于下面的示例数据sampleDT,对于在n次以下迭代拟合brms模型的任何帮助,以及每次从brmsfit对象中提取meanssigma,我将不胜感激。 {1}},并将它们添加到数据框brm.fit.n

如果sampleDT,则应该在数据框中添加10列n=10和10列means

我在下面的尝试无法按预期进行。它允许我运行brms模型sigma次,并生成nmeans sigma次,但是没有将它们添加到数据帧中-每种方式一列并按预期对每个运行的每个sigma分配一列。

#sample数据

n

#我的尝试

sampleDT<-structure(list(id = 1:10, N = c(10L, 10L, 10L, 10L, 10L, 10L, 
    10L, 10L, 10L, 10L), A = c(62L, 96L, 17L, 41L, 212L, 143L, 143L, 
    143L, 73L, 73L), B = c(3L, 1L, 0L, 2L, 170L, 21L, 0L, 33L, 62L, 
    17L), C = c(0.05, 0.01, 0, 0.05, 0.8, 0.15, 0, 0.23, 0.85, 0.23
    ), employer = c(1L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 0L, 0L), F = c(0L, 
    0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L), G = c(1.94, 1.19, 1.16, 
    1.16, 1.13, 1.13, 1.13, 1.13, 1.12, 1.12), H = c(0.14, 0.24, 
    0.28, 0.28, 0.21, 0.12, 0.17, 0.07, 0.14, 0.12), dollar.wage_1 = c(1.94, 
    1.19, 3.16, 3.16, 1.13, 1.13, 2.13, 1.13, 1.12, 1.12), dollar.wage_2 = c(1.93, 
    1.18, 3.15, 3.15, 1.12, 1.12, 2.12, 1.12, 1.11, 1.11), dollar.wage_3 = c(1.95, 
    1.19, 3.16, 3.16, 1.14, 1.13, 2.13, 1.13, 1.13, 1.13), dollar.wage_4 = c(1.94, 
    1.18, 3.16, 3.16, 1.13, 1.13, 2.13, 1.13, 1.12, 1.12), dollar.wage_5 = c(1.94, 
    1.19, 3.16, 3.16, 1.14, 1.13, 2.13, 1.13, 1.12, 1.12), dollar.wage_6 = c(1.94, 
    1.18, 3.16, 3.16, 1.13, 1.13, 2.13, 1.13, 1.12, 1.12), dollar.wage_7 = c(1.94, 
    1.19, 3.16, 3.16, 1.14, 1.13, 2.13, 1.13, 1.12, 1.12), dollar.wage_8 = c(1.94, 
    1.19, 3.16, 3.16, 1.13, 1.13, 2.13, 1.13, 1.12, 1.12), dollar.wage_9 = c(1.94, 
    1.19, 3.16, 3.16, 1.13, 1.13, 2.13, 1.13, 1.12, 1.12), dollar.wage_10 = c(1.94, 
    1.19, 3.16, 3.16, 1.13, 1.13, 2.13, 1.13, 1.12, 1.12)), row.names = c(NA, 
    -10L), class = "data.frame")

此问题也已发布here。预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

将现有代码改编为函数所需做的两件事是:

  • 重复健身n
  • 以良好的结构保存输出

有很多方法可以完成这两个部分,其中一个选项是purrr::map_dfr,可以同时执行两个操作,多次应用拟合并创建数据框。

我使用一个简单的线性模型来拟合随机数据,而不是brm模型,而是花了一些时间来拟合它们,您只需要用拟合代码替换这些部分并保存均值和sd而不是截距和斜率:

library(purrr)

# 1:10 - will repeat 10 times
map_dfr(1:10, function(i) {
    random_data = data.frame(
        x = rnorm(30),
        y = rnorm(30)
    )
    fit = lm(y ~ x, data = random_data)
    intercept = coef(fit)[1]
    slope = coef(fit)[2]
    return(data.frame(intercept, slope))
}, .id = "sim_num")

哪个给出数据帧作为输出:

   sim_num    intercept       slope
1        1  0.274903632 -0.03529736
2        2 -0.005134599 -0.22063748
3        3 -0.134999713  0.12090366
4        4 -0.216886033  0.21265679
5        5  0.261365432  0.02434036
6        6  0.067069791  0.23180334
7        7 -0.235138217  0.28360061
8        8 -0.117489553  0.10781101
9        9 -0.150288480  0.03086797
10      10 -0.031814194 -0.04075479