使用 lm 函数应用循环时出错

Error when applying loop with lm function

我正在尝试对数据框应用循环,以提取对每家公司进行的所有回归的贝塔值。 这是用作示例的数据的简化版本:

Dev_Panel_1 <- structure(list(companyID = c("A:GMGX", "A:GMGX", "A:GMGX", "A:GMGX", "A:GMGX", "A:GPTX", 
             "A:GPTX", "A:GPTX", "A:GPTX", "A:GPTX"), 
             year = c(2005, 2006, 2007, 2008, 2009, 1983, 1984, 1985, 
             1986, 1987), 
             Profitability = c(0.76, 0.1, -0.01, -0.1, 0.04, 
             0.07, 0.06, 0.05, 0.05, 0.11), 
             Otminus1 = c(-0.28, -0.28, 
             -0.44, -0.27, 0.23, 0.11, -0.01, -0.01, 0.02, -0.04)), 
             row.names = c(NA, -10L), class = "data.frame")

这是我用于提取 betas 的代码:

betas_Dev <- matrix(nrow=length(unique(Dev_Panel_1$companyID)), ncol=2)

colnames(betas_Dev) <- c("Intercept", "beta")

for (i in 1:length(unique(Dev_Panel_1$companyID))) {
        betas_Dev_e[i,] <- coef(lm(Otminus1~Profitability, Dev_Panel_1[Dev_Panel_1$companyID==i,]))}

Dev_Panel_1$betas_ <- rep(betas[,2],each=10)

当运行循环时我得到错误信息:

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, …) : 0 (non-NA)

我在多个问题中了解到这个问题,例如:

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 0 (non-NA) cases Calls: lm -> lm.fit

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) 0 non-na cases

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 0 (non-NA) cases but there is NO NA

但到目前为止 none 所提供的解决方案已经奏效。

试试这个:

vec <- unique(Dev_Panel_1$companyID)
result <- vector('list', length(vec))

for (i in seq_along(vec)) {
  result[[i]] <- coef(lm(Otminus1~Profitability, Dev_Panel_1, companyID==vec[i]))
}

mat <- do.call(rbind, result)
mat
#     (Intercept) Profitability
#[1,]     -0.1961       -0.0756
#[2,]      0.0568       -0.6290