R 使用2个自变量运行所有可能的线性回归组合
我想为每2个自变量运行所有可能的组合(OLS回归)。我有一个csv,其中有我的数据(只有一个因变量和23个自变量),我尝试将数据库中的变量从a重命名为z,我将“y”称为我的因变量(一个名为“y”的列,它是我的因变量),以便由以下代码识别:R 使用2个自变量运行所有可能的线性回归组合,r,R,我想为每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 <-
#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))
#所有组合
您应该将您的文本表单
指定为公式:
KOFS05.12调用:
#>lm(公式=i,数据=KOFS05.12)
#>
#>系数:
#>(截取)a b
#> 0.19763 -0.15873 0.02854
#>
#>
#> [[2]]
#>
#>电话:
#>lm(公式=i,数据=KOFS05.12)
#>
#>系数:
#>(截取)a c
#> 0.21395 -0.15967 0.05737
#>
#>
#> [[3]]
#>
#>电话:
#>lm(公式=i,数据=KOFS05.12)
#>
#>系数:
#>(截取)b c
#> 0.157140 0.002523 0.028088
由(v1.0.0)于2021年2月17日创建,如问题下方的注释所述,检查您是否需要y或y。解决后,我们可以使用其中任何一个。不需要重命名这些列。我们使用内置的mtcars
数据集作为示例,因为问题中没有提供测试数据。(以后请始终提供。)
1)ExtreatveSearch此功能运行速度非常快,因此您也可以尝试高于2的组合
library(ExhaustiveSearch)
ExhaustiveSearch(mpg ~., mtcars, combsUpTo = 2)
2)combn使用下面定义的lmfun
功能和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)
您是否有一个名为Y
或Y
的列?您是否可以使用dput
即dput(head(KOFS05.12))
编辑您的帖子,以包含数据的前几行?作为。不需要公式。如果你删除它,它仍然可以工作,并给出相同的输出。哇-不知道,谢谢!!!穷尽搜索和Akaike方法解决了我寻找最佳统计显著性的问题
# 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)