假设这是我的代码:
library(magrittr)
library(dplyr)
set.seed(123,kind="Mersenne-Twister",normal.kind="Inversion")
y = runif(20,0,50)
simulation <- function(y){
x <- rnorm(length(y),3,0.125)
lm(y ~ x)
}
fit <- lapply(1:10, function(dummy) simulation(y))
coef <- sapply(fit, coef) %>%
t() %>%
as.data.frame()如何在数据帧中收集从函数x生成的10个模拟simulation变量?
发布于 2022-01-06 17:59:23
它们存储在fit对象中。用fit[[1]]$model$x可以提取出一个单一的。通过编程,我们可以在这样的数据框架中获得所有这些数据:
xs = lapply(fit, \(x) x$model$x)
data.frame(i = rep(seq_along(xs), lengths(xs)), x = unlist(xs))
# i x
# 1 1 3.153010
# 2 1 3.044977
# 3 1 3.050096
# 4 1 3.013835
# 5 1 2.930520
# 6 1 3.223364
# 7 1 3.062231
# ...或者,如果你想要更多的信息,你可以用broom::augment代替。这将返回全部数据,以及预测值、残差等。
result = bind_rows(lapply(fit, broom::augment), .id = "sim")
head(result)
# A tibble: 6 × 9
# sim y x .fitted .resid .hat .sigma .cooksd .std.resid
# <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 1 14.4 3.15 19.2 -4.78 0.141 15.1 0.0101 -0.350
# 2 1 39.4 3.04 24.6 14.8 0.0612 14.7 0.0353 1.04
# 3 1 20.4 3.05 24.3 -3.89 0.0633 15.1 0.00252 -0.273
# 4 1 44.2 3.01 26.2 18.0 0.0525 14.5 0.0437 1.26
# 5 1 47.0 2.93 30.4 16.7 0.0603 14.6 0.0438 1.17
# 6 1 2.28 3.22 15.6 -13.3 0.234 14.7 0.164 -1.04 你也可能喜欢bind_rows(lapply(fit, broom::tidy), .id = "sim"),它会给你每一个系数一行,而bind_rows(lapply(fit, broom::glance), .id = "sim")给你每一个模型一行。
https://stackoverflow.com/questions/70611365
复制相似问题