如何 运行 每个行业年的线性回归模型,不包括 R 中的公司 i 观察值?

How to run linear regression model for each industry-year excluding firm i observations in R?

这是我的数据集在 R 中的 dput 输出……

data1<-structure(list(Year = c(1998, 1999, 1999, 2000, 1996, 2001, 1998, 
1999, 2002, 1998, 2005, 1998, 1999, 1998, 1997, 1998, 2000), 
    `Firm name` = c("A", "A", "B", "B", "C", "C", "D", "D", "D", 
    "E", "E", "F", "F", "G", "G", "H", "H"), Industry = c("AUTO", 
    "AUTO", "AUTO", "AUTO", "AUTO", "AUTO", "AUTO", "AUTO", "AUTO", 
    "Pharma", "Pharma", "Pharma", "Pharma", "Pharma", "Pharma", 
    "Pharma", "Pharma"), X = c(1, 2, 5, 6, 7, 9, 10, 11, 12, 
    13, 15, 16, 17, 18, 19, 20, 21), Y = c(30, 31, 34, 35, 36, 
    38, 39, 40, 41, 42, 44, 45, 46, 47, 48, 49, 50), Z = c(23, 
    29, 47, 53, 59, 71, 77, 83, 89, 95, 107, 113, 119, 125, 131, 
    137, 143)), row.names = c(NA, -17L), class = c("tbl_df", 
"tbl", "data.frame"), na.action = structure(c(`1` = 1L), class = "omit"))
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50), Z = c(23, 
29, 35, 41, 47, 53, 59, 65, 71, 77, 83, 89, 95, 101, 107, 113, 
119, 125, 131, 137, 143)), row.names = c(NA, -21L), class = c("tbl_df", 
"tbl", "data.frame"), na.action = structure(c(`1` = 1L), class = "omit"))

这里我试图对每个行业年份进行回归 Y~ X+Z 但不包括公司 i observations.For 每个公司我想估计线性回归模型 使用所有行业同行公司'观察但不包括公司自己的观察。例如;对于公司 A,我想通过使用其行业同行公司(B、C 和 D)的所有观察来对 Y~ X+Z 进行回归,但不包括公司 A观察。同样,我想 运行 通过使用公司 A、C 和 D(与 B 属于同一行业的一部分)的所有观察来为公司 B 建模,但不包括公司 B 的观察。同样的程序也适用于 C & D 公司。我想为每个行业的每个公司做这个练习。请帮忙。

显示的代码不便于阅读。但是从你写的内容来看,我建议使用嵌套循环,例如:

for(y in year){
    for(comp in FirmName){
      # transform data : select only companys in this industry, but exclude comp
       lm(..)
     }
 }

如@bonedi 所述,您可以使用嵌套循环来完成此操作。如果您想为单个行业-年份组合创建模型,则需要按 IndustryYear 对数据进行子集化。您可以遍历 Firm name 并在创建模型之前排除该公司。结果可以存储在一个列表中,以行业-年份-公司命名。这不是一个很好的解决方案,但它应该让你更接近。

lst <- list()

for (ind in unique(data1$Industry)) {
  for (year in unique(data1[data1$Industry == ind, ]$Year)) {
    for (firm in unique(data1[data1$Industry == ind & data1$Year == year, ]$`Firm name`)) {
      sub_data <- data1[data1$Industry == ind & data1$Year == year & data1$`Firm name` != firm, ]
      if (nrow(sub_data) > 0) {
        name <- paste(ind, year, firm, sep = '-')
        lst[[name]] <- lm(Y ~ X + Z, data = sub_data)
      }
    }
  }
}