对于R中分为N个块的数据运行迭代回归

问题描述 投票:0回答:1

我有一个结构如下的数据框:

birthwt  tobacco01  pscore  pscoreblocks
3425     0          0.18    (0.177, 0.187]
3527     1          0.15    (0.158, 0.168]
1638     1          0.34    (0.335, 0.345]

birthwt列是一个连续变量,以克为单位来衡量出生体重。 pepper01列包含0或1的值。pscore列包含0到1之间的概率值。pscoreblocks将pscore列分解为100个大小相等的块。

我正在尝试找到一种有效的方法来对pscoreblocks中的每个块执行以下操作。我已经包含了在整个数据集上运行而不分割成块的代码。

1-运行回归。

one <- lm(birthwt ~ tobacco01, dfc)

2-求回归中bacco01变量的系数值。

two <- summary(one)$coefficients[2,1]

3-该系数值乘以:[(该区块中烟草= 1的人数)+(烟草的人数=烟草==在该区块中为0)] /(该区块中的总人数块)

two_5 <- ((sum(dfc$tobacco01 == 1)) + (sum(dfc$tobacco01 == 0)))/ sum(dfc$tobacco)

three <- two*two_5

4-最后,我希望能够将(100)的所有(3)中的值相加。

我知道如何分别执行每个步骤,但是我不知道如何在100个单独的块中进行迭代。我尝试使用group_by(pscoreblocks),然后运行回归,但看起来group_by()和lm()不能很好地协同工作。我还考虑过使用ivot_longer()为每个块创建一个单独的列,然后尝试使用该格式的数据运行回归。我非常感谢有关如何迭代所有100个块的任何建议。

r loops regression apply
1个回答
0
投票

该问题可能是项目模块。

[我相信,问题中的两个主要痛点是1和2。因此回答那些。

步骤:

  1. 将数据集嵌套到pscoreblocks

    d_nested <- d %>% group_by(pscoreblocks) %>% nest()

  2. 编写要建模的函数。

    mod_fun <- function(df){ lm( birthwt ~ tobacco01, data = df) }

  3. 使用上述功能进行建模。

    m_d <- d_nested %>% mutate(model = map(data, mod_fun))

  4. 创建另一个函数以提取每个模型的系数。

    b_fun <- function(mod){ coefficients(mod)[[1]] }

  5. 最后,使用上述功能。

    m_d %>% transmute(coeff = map_dbl(model, b_fun))

将为您提供输出[系数与数据相同,因为每个组只有一个数据点] as

# A tibble: 3 x 2
# Groups:   pscoreblocks [3]
  pscoreblocks   coeff
  <chr>          <dbl>
1 (0.177, 0.187]  3425
2 (0.158, 0.168]  3527
3 (0.335, 0.345]  1638

数据:

structure(list(birthwt = c(3425, 3527, 1638), tobacco01 = c(0, 
1, 1), pscore = c(0.18, 0.15, 0.34), pscoreblocks = c("(0.177, 0.187]", 
"(0.158, 0.168]", "(0.335, 0.345]")), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame")) -> d
© www.soinside.com 2019 - 2024. All rights reserved.