简体   繁体   English

运行多次线性回归 model

[英]Run many linear regression model

Suppose that I have data in order to run many linear regression model.假设我有数据可以运行许多线性回归 model。

Data: https://www.img.in.th/image/TNHdEq数据: https://www.img.in.th/image/TNHdEq

Given column C1 is y variable.给定 C1 列是 y 变量。

x variable is column C4 by create from column C2 and C3, Model1 is created by first row of column C2 and 8 rows remaining of column C3, Model2 is created by first 2 rows of column C2 and 7 rows remaining C3, Then to Model9 is created by first 8 rows of C2 and last row of C3. x 变量是 C4 列,由 C2 和 C3 列创建,Model1 由 C2 列的第一行和 C3 列剩余 8 行创建,Model2 由 C2 列的前 2 行和 C3 剩余 7 行创建,然后到 Model9 是由 C2 的前 8 行和 C3 的最后一行创建。

Example x variable:示例 x 变量:

model1 : { b, d, i,...,z}

model2 : { b, f, i,..., z}

.

.

.

model9 : {b, f, h,..., z}

And select models by maximum R squared.和 select 模型最大 R 平方。

Question: How to code for it?问题:如何编码? loop?环形?

Using both R and python.同时使用 R 和 python。

Ps.Really, I use ordered probit model.And I have many rows 100+. Ps.真的,我使用有序概率 model。我有很多行 100+。

Thank you.谢谢你。

To run many models can be done with *apply loops and the results output to a list object.要运行许多模型,可以使用*apply循环和结果 output 到列表 object 来完成。 In this case the loop variable will be the row number i , varying from 1 to nrow(df1) - 1 .在这种情况下,循环变量将是行号i ,从 1 变化到nrow(df1) - 1

n <- nrow(df1)
probit_list <- lapply(seq.int(n)[-n], function(i){
  C4 <- c(df1$C2[seq.int(i)], df1$C3[-seq.int(i)])
  C4 <- ordered(C4, levels = levels(df1$C2))
  dftmp <- data.frame(C1 = df1$C1, C4)
  tryCatch(glm(C1 ~ C4, data = dftmp, family = binomial(link = "probit")),
           error = function(e) e)
})

To see how many gave error run看看有多少给出错误运行

ok <- sapply(probit_list, inherits, "error")
sum(!ok)

Test data测试数据

set.seed(1234)
n <- 9
df1 <- data.frame(
  C1 = rbinom(n, 1, prob = c(0.4, 0.6)),
  C2 = ordered(sample(1:4, n, TRUE), levels = 1:4),
  C3 = ordered(sample(1:4, n, TRUE), levels = 1:4)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM