簡體   English   中英

運行具有 2 個自變量的線性回歸的所有可能組合

[英]Run all posible combination of linear regression with 2 independent variables

我想為每 2 個自變量(OLS 回歸)運行所有可能的組合。 我有一個 csv ,其中有我的數據(只有一個因變量和 23 個自變量),我嘗試將我的數據庫中的變量從 a 重命名為 z,我將 'y' 稱為我的因變量(一列名稱“y”這是我的因變量)由以下代碼識別:

#all the combinations
all_comb <- combn(letters, 2)

#create the formulas from the combinations above and paste
text_form <- apply(all_comb, 2, function(x) paste('Y ~', paste0(x, collapse = '+')))

lapply(text_form, function(i) lm(i, data= KOFS05.12))

但顯示此錯誤:

Error in eval(predvars, data, env): object 'y' not found

我需要知道 R 平方

任何想法讓它工作並運行每一個可能的回歸?

如問題下的評論中所述,檢查您是否需要 y 或 Y。解決后我們可以使用其中任何一個。 無需重命名列。 我們使用內置的mtcars數據集作為示例,因為問題中沒有提供測試數據。 (請始終在將來提供。)

1) ExhaustiveSearch這運行速度非常快,因此您也可以嘗試高於 2 的組合。

library(ExhaustiveSearch)
ExhaustiveSearch(mpg ~., mtcars, combsUpTo = 2)

2) combn使用下面定義的lmfun function 和combn

dep <- "mpg"  # name of dependent variable
nms <- setdiff(names(mtcars), dep)  # names of indep variables
lmfun <- function(x, dep) do.call("lm", list(reformulate(x, dep), quote(mtcars)))

lms <- combn(nms, 2, lmfun, dep = dep, simplify = FALSE)
names(lms) <- lapply(lms, formula)

3) listcompr使用上面的lmfun和 listcompr 我們可以使用以下內容。 請注意,我們需要版本 0.1.1 或更高版本的 listcompr,它尚未在 CRAN 上,因此我們從 github 獲得它。

# install.github("patrickroocks/listcompr")
library(listcompr)
packageVersion("listcompr") # need version 0.1.1 or later

dep <- "mpg"  # name of dependent variable
nms <- setdiff(names(mtcars), dep)  # names of indep variables

lms2 <- gen.named.list("{nm1}.{nm2}", lmfun(c(nm1, nm2), dep), 
  nm1 = nms, nm2 = nms, nm1 < nm2)

您應該將您的text_form指定為公式:

KOFS05.12 <- data.frame(y = rnorm(10),
                        a = rnorm(10),
                        b = rnorm(10),
                        c = rnorm(10))

all_comb <- combn(letters[1:3], 2)
fmla_form <- apply(all_comb, 2, function(x) as.formula(sprintf("y ~ %s", paste(x, collapse = "+"))))
lapply(fmla_form, function(i) lm(i, KOFS05.12))
#> [[1]]
#> 
#> Call:
#> lm(formula = i, data = KOFS05.12)
#> 
#> Coefficients:
#> (Intercept)            a            b  
#>     0.19763     -0.15873      0.02854  
#> 
#> 
#> [[2]]
#> 
#> Call:
#> lm(formula = i, data = KOFS05.12)
#> 
#> Coefficients:
#> (Intercept)            a            c  
#>     0.21395     -0.15967      0.05737  
#> 
#> 
#> [[3]]
#> 
#> Call:
#> lm(formula = i, data = KOFS05.12)
#> 
#> Coefficients:
#> (Intercept)            b            c  
#>    0.157140     0.002523     0.028088

代表 package (v1.0.0) 於 2021 年 2 月 17 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM