【问题标题】:How do you extract the coefficient and standard error from the lm() loop?如何从 lm() 循环中提取系数和标准误差?
【发布时间】:2021-04-30 17:44:13
【问题描述】:

我正在查看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])

【问题讨论】:

  • cfs &lt;- lapply(lm.test, coef) 不是已经给出了你想要的吗?为什么要在其中添加额外的[1:2]?顺便说一句,你想要的可以通过使用匿名函数lapply(lm.test, function(x) coef(x)[1:2]) 来实现

标签: r loops regression


【解决方案1】:

我可能有一种更优雅的方式来提取系数和 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)

【讨论】:

    【解决方案2】:

    啊,你得到了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)
    

    【讨论】:

    • 我得到了 cf_i 的以下信息:(Intercept) wt 37.285126 -5.344472 而不是 SE。
    • SE 是一个单独的计算,而不是 lm() 输出的默认部分,因此无法直接从您创建的对象中提取它 afaik
    猜你喜欢
    • 2014-08-09
    • 2012-06-21
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    相关资源
    最近更新 更多