[英]How to Loop/Repeat a Linear Regression in R
我已經想出了如何在 R 中使用 4 個變量制作表格,我將其用於多元線性回歸。 每個回歸的因變量 (Lung) 取自包含 22,000 列的 csv 表的一列。 自變量之一(血液)取自類似表的相應列。 每列代表一個特定基因的水平,這就是為什么有這么多基因。 還有兩個額外的變量(每個患者的年齡和性別)。 當我輸入線性回歸方程時,我使用 lm(Lung[,1] ~ Blood[,1] + Age + Gender),它適用於一個基因。 我正在尋找一種方法來輸入這個方程,並讓 R 計算肺和血液的所有剩余列,並希望將系數輸出到表格中。 任何幫助,將不勝感激!
您想運行 22,000 次線性回歸並提取系數嗎? 從編碼的角度來看,這很容易做到。
set.seed(1)
# number of columns in the Lung and Blood data.frames. 22,000 for you?
n <- 5
# dummy data
obs <- 50 # observations
Lung <- data.frame(matrix(rnorm(obs*n), ncol=n))
Blood <- data.frame(matrix(rnorm(obs*n), ncol=n))
Age <- sample(20:80, obs)
Gender <- factor(rbinom(obs, 1, .5))
# run n regressions
my_lms <- lapply(1:n, function(x) lm(Lung[,x] ~ Blood[,x] + Age + Gender))
# extract just coefficients
sapply(my_lms, coef)
# if you need more info, get full summary call. now you can get whatever, like:
summaries <- lapply(my_lms, summary)
# ...coefficents with p values:
lapply(summaries, function(x) x$coefficients[, c(1,4)])
# ...or r-squared values
sapply(summaries, function(x) c(r_sq = x$r.squared,
adj_r_sq = x$adj.r.squared))
模型存儲在一個列表中,其中模型 3(帶有 DV Lung[, 3] 和 IVs Blood[,3] + Age + Gender)在my_lms[[3]]
,依此類推。 您可以使用列表上的應用函數進行匯總,從中可以提取您想要的數字。
問題似乎是關於如何使用在循環內修改的公式調用回歸函數。
以下是您可以這樣做的方法(使用鑽石數據集):
attach(ggplot2::diamonds)
strCols = names(ggplot2::diamonds)
formula <- list(); model <- list()
for (i in 1:1) {
formula[[i]] = paste0(strCols[7], " ~ ", strCols[7+i])
model[[i]] = glm(formula[[i]])
#then you can plot or do anything else with the result ...
png(filename = sprintf("diamonds_price=glm(%s).png", strCols[7+i]))
par(mfrow = c(2, 2))
plot(model[[i]])
dev.off()
}
明智與否,要使循環至少以某種方式工作,您需要:
y<- c(1,5,6,2,5,10) # response
x1<- c(2,12,8,1,16,17) # predictor
x2<- c(2,14,5,1,17,17)
predictorlist<- list("x1","x2")
for (i in predictorlist){
model <- lm(paste("y ~", i[[1]]), data=df)
print(summary(model))
}
粘貼功能將解決問題。
一個 tidyverse 添加 - 使用 map()
另一種方法 - 使用purrr
包中的map2()
:
library(purrr)
xs <- anscombe[,1:3] # Select variables of interest
ys <- anscombe[,5:7]
map2_df(ys, xs,
function(i,j){
m <- lm(i ~j + x4 , data = anscombe)
coef(m)
})
輸出是所有系數的數據幀(tibble):
`(Intercept)` j x4
1 4.33 0.451 -0.0987
2 6.42 0.373 -0.253
3 2.30 0.526 0.0518
如果更多變量正在改變,這可以使用pmap()
函數來完成
您能幫我如何循環獲得VIF和confint(系數的置信區間)。 對上述代碼進行一些小的更正確實很有幫助。
y<- c(1,5,6,2,5,10) # response
x1<- c(2,12,8,1,16,17) # predictor
x2<- c(2,14,5,1,17,17)
df<-cbind(y,x1,x2)
df<-as.data.frame(df)
predictorlist<- list("x1","x2")
for (i in predictorlist){
model <- lm(paste("y ~", i[[1]]), data=df)
print(summary(model))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.