I have asked a previous question (Splitting data and running linear regression loop), and a great solution was provided using tidyverse and pipes. I am saving off the p-values of my parameters for the 4,000 'keys' in the data, putting them into separate dataframe and then running some histograms and other visuals to examine the significance of the parameter for each of the 4,000 keys. This worked the first few times I was running it, but running the exact same code on different parameters/predictors, I continually recieve an error saying:
Error in summary(lm(y1 ~ x1 + x2 ))$coefficients['x1', : subscript out of bounds
If i run a single model on that key and look at the summary, the pvalue definitely exists in the position [x1,4] or [2,4], but it won't return in the model. Sometimes it will run, but then bomb out on [3,4] or [4,4], etc.
Someone has suggested that tidyverse is killing the memory, thus bombing it out. I know it isn't the code, because it will sometimes work, or sometimes progress further than other times, but it just seems odd. So, would data.table be a better solution to loop over the entire dataset? I am not familiar with how to chain together data.table, so how would I recreate the following code using data.table to run a model over each of 4,000 keys that I have with the 10+ parameters that I have.
df
Key y1 x1 x2
A 10 1 3
A 11 2 4
A 12 3 5
B 13 4 6
B 14 5 7
B 15 6 8
C 16 7 9
C 17 8 1
C 18 9 2
df %>% group_by(Key) %>%
summarise(Intercept = lm(y1 ~ x1 + x2)$coefficients[1],
Coeff_x1 = lm(y1 ~ x1 + x2)$coefficients[2],
Coeff_x2 = lm(y1 ~ x1 + x2)$coefficients[3],
R2 = summary(lm(y1 ~ x1 + x2))$r.squared,
pvalue = summary(lm(y1 ~ x1 + x2))$coefficients["x1",4])
# A tibble: 3 x 6
Key Intercept Coeff_x1 Coeff_x2 R2 pvalue
<chr> <dbl> <dbl> <dbl> <dbl> <dbl>
1 A 9. 1.00 NA 1 8.00e-16
2 B 9. 1.00 NA 1 7.00e-16
3 C 9. 1.00 7.86e-16 1 NaN