1
votes

I'm trying to apply a loop to a data frame in order to extract the betas of all regressions conducted on each company. Here's a shortened version of the data to use as an example:

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")

This is the code I'm using for this for the extraction of 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)

When running the loop I get the error message:

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

I've read about this problem in multiple questions such as:

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

but none of the provided solutions have worked so far.

1

1 Answers

1
votes

Try using this :

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