0

I am trying to run a simple OLS regression for each share against the market index. I am struggling to write a for-loop to automate this process (newbie to R!)

My for-loop needs to achieve the following: for each share in my sample, I need to create a time series of that share. I then need to regress this particular share against the market index (which was already imported). I have created a file called "test", which has the name of each share in 1 column, and need help writing the code to loop through each share. Each share (and market index) has the same number of observations (321) and there are 1400 shares.

When running the below, IBMt appears to output a matrix of share names instead of the 321 returns for a particular share (where in my mind the last share in my list should be stored as the value for the vector IBMt)

for (val in test) {
IBMt<- as.ts(val)
ols.fit = lm(IBMt ~ SP500t)
summary(ols.fit)}
  • I think you'll want to use `lapply` or `map` here instead of a `for` loop. If you can write a function that works for a single series, you can then just plop that function into a call to `lapply` iterated over a vector of share names or something along those lines. – ulfelder Dec 26 '19 at 12:40
  • Welcome to SO! Please make your question [reproducible](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – s__ Dec 27 '19 at 07:43

0 Answers0