首页 > 解决方案 > 从 R 中的函数中提取 T 统计量

问题描述

我有这个函数,它是从一本教科书中得到的,它运行几个线性回归,然后为每个回归保存 P 值。

我也想保存 T-Statistic,但我很难找到正确的语法来输入 select 函数。

这是当前功能。

models <- lapply(paste(factors, ' ~  a + b + c + d + e + f + g + h+ j -',factors),
             function(f){ lm(as.formula(f), data = df) %>%               # Call lm(.)
                 summary() %>%                               # Gather the output
                 "$"(coef) %>%                               # Keep only the coefs
                 data.frame() %>%                            # Convert to dataframe
                 filter(rownames(.) == "(Intercept)") %>%    # Keep only the Intercept
                 dplyr::select(Estimate,`Pr...t..`)})         # Keep the coef & p-value

我知道我必须更改函数的最后一部分:dplyr::select(Estimate,`Pr...t..`)但经过所有的研究和反复试验,我仍然卡住了。

这是使用 mtcars 数据的可重现示例。

library(dplyr)

df <- mtcars

df <- df %>% 
  select(1,2,3,4,5,6,7)

factors <- c("mpg", "cyl", "disp", "hp", "drat", "wt")

models <- lapply(paste(factors, ' ~  mpg + cyl + disp + hp + drat + wt -',factors),
                 function(f){ lm(as.formula(f), data = df) %>%               # Call lm(.)
                     summary() %>%                               # Gather the output
                     "$"(coef) %>%                               # Keep only the coefs
                     data.frame() %>%                            # Convert to dataframe
                     filter(rownames(.) == "(Intercept)") %>%    # Keep only the Intercept
                     dplyr::select(Estimate,`Pr...t..`)}         # Keep the coef & p-value
)


final <- matrix(unlist(models), ncol = 2, byrow = T) %>%       # Switch from list to dataframe
  data.frame(row.names = factors


标签: r

解决方案


你的例子对我有用。你可以让它更“整洁”一点,如下所示:

library(broom)

sumfun <- function(f) {
  lm(as.formula(f), data = df) %>%          
    tidy() %>%
    filter(term == "(Intercept)") %>%
    dplyr::select(estimate, p.value)
}
pp <- paste(factors, ' ~  mpg + cyl + disp + hp + drat + wt -',factors)
names(pp) <- factors
final <- purrr::map_dfr(pp, sumfun, .id = "factor")

推荐阅读