I have a data frame similar to the following with a total of 500 columns:
Probes <- data.frame(Days=seq(0.01, 4.91, 0.01), B1=5:495,B2=-100:390, B3=10:500,B4=-200:290)
I would like to calculate a rolling window linear regression where my window size is 12 data points and each sequential regression is separated by 6 data points. For each regression, "Days" will always be the x component of the model, and the y's would be each of the other columns (B1, followed by B2, B3, etc). I would then like to save the co-efficients as a dataframe with the existing column titles (B1, B2, etc).
I think my code is close, but is not quite working. I used rollapply from the zoo library.
slopedata<-rollapply(zoo(Probes), width=12, function(Probes) {
coef(lm(formula=y~Probes$Days, data = Probes))[2]
}, by = 6, by.column=TRUE, align="right")
If possible, I would also like to have the "xmins" saved to a vector to add to the dataframe. This would mean the smallest x value used in each regression (basically it would be every 6 numbers in the "Days" column.) Thanks for your help.
try this:
You can also use the
rollRegres
package as followsThe solution is a lot faster than e.g., the
zoo
solutionAt present you though need to install the package from Github due to an error in the validation in version
0.1.0
. Thus, run1) Define a zoo object
z
whose data containsProbes
and whose index is taken from the first column of Probes, i.e.Days
. Noting thatlm
allowsy
to be a matrix define acoefs
function which computes the regression coefficients. Finallyrollapply
overz
. Note that the index of the returned object gives xmin.giving:
Note that
DF <- fortify.zoo(rz)
could be used if you needed a data frame representation ofrz
.2) An alternative somewhat similar approch would be to
rollaplly
over the row numbers: