假設我有一個這樣的模型。
set.seed(416)
N = 100
X = data.frame(
x1 <- rnorm(N,0,1),
x2 <- rnorm(N,0,1)
)
X$y <- 2*X$x1 3*X$x2 rnorm(N)
model <- lm(y ~ x1 x2, data=X)
我想為每個變數創建一個包含估計值、P 值和 Sig(無論 p < 0.05)的命名串列。這就是我現在的做法。但是有沒有辦法在 for 回圈中執行此操作,以便我可以輕松地向模型添加更多變數?
# Inefficient
model_data <- (c(
est_x1= coef(summary(model))['x1', 'Estimate'],
p_x1=coef(summary(model))['x1', 'Pr(>|t|)'],
sig_x1=coef(summary(model))['x1', 'Pr(>|t|)'] < 0.05,
est_x2= coef(summary(model))['x2', 'Estimate'],
p_x2= coef(summary(model))['x2', 'Pr(>|t|)'],
sig_x2=coef(summary(model))['x2', 'Pr(>|t|)'] < 0.05
))
est_x1 p_x1 sig_x1 est_x2 p_x2 sig_x2
1.947646e 00 1.204075e-34 1.000000e 00 3.008251e 00 1.158695e-51 1.000000e 00
uj5u.com熱心網友回復:
broom 包可以采用模型并將結果放入 data.frame
model <- lm(y ~ x1 x2, data=X)
library(broom)
summary_table <- tidy(model)
summary_table
# A tibble: 3 × 5
term estimate std.error statistic p.value
<chr> <dbl> <dbl> <dbl> <dbl>
1 (Intercept) 0.106 0.101 1.05 2.94e- 1
2 x1 1.95 0.102 19.1 1.20e-34
3 x2 3.01 0.0982 30.6 1.16e-51
要創建命名向量:
answer <- c(summary_table$estimate, summary_table$std.error, summary_table$p.value)
names <- expand.grid(summary_table$term, c("estimate", "std.error", "p.value"), stringsAsFactors = FALSE)
names(answer) <- paste(names$Var2, names$Var1)
answer
estimate (Intercept) estimate x1 estimate x2 std.error (Intercept) std.error x1 std.error x2 p.value (Intercept)
1.059576e-01 1.947646e 00 3.008251e 00 1.005028e-01 1.019442e-01 9.822749e-02 2.943759e-01
p.value x1 p.value x2
1.204075e-34 1.158695e-51
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/536373.html
標籤:r工作室我lme4
