r - 从 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
解决方案
你的例子对我有用。你可以让它更“整洁”一点,如下所示:
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")
推荐阅读
- go - 如何在 Golang 中正确使用可变参数 args?
- html - 为什么我的 GET 请求参数没有显示在我的 url 中?
- javascript - 400 Bad Request for POST to API for js app,但不是 asp.net mvc app
- leaflet - 控制键激活时禁用 boxZoom
- javascript - 在字符类中如何解释单词字符?
- makefile - 当我检查 leptonica 时,我收到了 FAIL 消息
- java - this.object.method(this) 有什么作用?
- reactjs - 在 ComponentWillUnmount 的 React 组件中停止网络摄像头
- python - 如何修复我的井字游戏的极小极大算法
- ios - 为什么我的 Heroku 打开应用程序按钮不起作用?