你如何从 lm() 循环中提取系数和标准误差?

时间:2021-01-26 21:57:30

标签: r loops regression

我正在研究从回归循环中提取系数的 this post。我想知道如何提取系数和标准误差?我以为它会是这样的,但似乎不是这样的:

data <- mtcars[, c("mpg", "cyl", "disp", "hp", "drat", "wt")]
col10 <- names(data)[-1]

lm.test <- vector("list", length(col10))

for(i in seq_along(col10)){
  lm.test[[i]] <- lm(reformulate(col10[i], "mpg"), data = data)
}

lm.test

cfs <- lapply(lm.test, coef[1:2])

2 个答案:

答案 0 :(得分:0)

啊,你得到了 famous "object of type closure is not subsettable" error

我们可以使用一些 [[ 魔法来帮助我们:

cfs <- lapply(lm.test, `[[`, "coefficients")

双括号是一个提取变量名称的函数 - 这有效地循环了以下代码:

cf_i <- lm.test[[i]][["coefficients"]]

其中 i 是 lm.test 中的模型数量

编辑:

更简单,

cfs <- lapply(lm.test, coef)

答案 1 :(得分:0)

我可能有一种更优雅的方法来提取系数和 SE,但这就是我所做的:

data <- mtcars[, c("mpg", "cyl", "disp", "hp", "drat", "wt")]
col10 <- names(data)[-1]

lm.test <- vector("list", length(col10))

for(i in seq_along(col10)){
  lm.test[[i]] <- lm(reformulate(col10[i], "mpg"), data = data)
}

lm.test_coef <- lapply(lm.test, summary)

# extract the coefficient (X2)
lm.test_coef_df <- data.frame(matrix(unlist(lm.test_coef), ncol = max(lengths(lm.test_coef)), byrow = TRUE))

# turn list into dataframe
lm.test_coef_df <- as.data.frame(t(simplify2array(lm.test_coef)))

# extract coefficients column
lm.test_coef_df_i <- dplyr::select(lm.test_coef_df, terms, coefficients)

# flatten list
lm.test_coef_df_i <- apply(lm.test_coef_df_i,2,as.character)
View(lm.test_coef_df_i)
lm.test_coef_df_i <- as.data.frame(lm.test_coef_df_i)

# remove strings
lm.test_coef_df_i$coefficients <- stringr::str_replace(lm.test_coef_df_i$coefficients, '\\c', '')
lm.test_coef_df_i$coefficients <- stringr::str_replace(lm.test_coef_df_i$coefficients, '\\(', '')
lm.test_coef_df_i$coefficients <- stringr::str_replace(lm.test_coef_df_i$coefficients, '\\)', '')


lm.test_coef_df_i <- cSplit(lm.test_coef_df_i, "coefficients", sep=",")

lm.coef_sd <- dplyr::select(lm.test_coef_df_i, coefficients_2, coefficients_4)
View(lm.coef_sd)
相关问题