I have seen a lot of similar questions, but there is one key to the loop that I am trying to write that I am missing. I have a a set of dataset with ~4,000 different keys, and for each key, there are ~1,000 observations. I have filtered out a key to isolate the observations for that key, run linear regression, checked model assumptions and all looks good. However, I want to loop over this dataset and run that linear regression for each of the keys. Then I will want to store the coefficients, pvalues, R^2, etc and review them together.
Here is a sample of my data:
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
I have run:
datA <- data %>% filter(key=='A')
lm(y1 ~ x1 + x2, data = datA)
And then repeated that for keys B and C. Each question that I have seen on here is looking at the looping over the different variables for the entire set, but not splitting the data on the rows.
But I need to do this 4,000 more times. Any assistance to write this loop would be greatly appreciated (I am terrible at writing loops).