I want to carry out a linear regression in R for data in a normal and in a double logarithmic plot.
For normal data the dataset might be the follwing:
lin <- data.frame(x = c(0:6), y = c(0.3, 0.1, 0.9, 3.1, 5, 4.9, 6.2))
plot (lin$x, lin$y)
There I want to calculate draw a line for the linear regression only of the datapoints 2, 3 and 4.
For double logarithmic data the dataset might be the following:
data = data.frame(
x=c(1:15),
y=c(
1.000, 0.742, 0.623, 0.550, 0.500, 0.462, 0.433,
0.051, 0.043, 0.037, 0.032, 0.028, 0.025, 0.022, 0.020
)
)
plot (data$x, data$y, log="xy")
Here I want to draw the regression line for the datasets 1:7 and for 8:15.
Ho can I calculate the slope and the y-offset als well as parameters for the fit (R^2, p-value)?
How is it done for normal and for logarithmic data?
Thanks for you help,
Sven
In R, linear least squares models are fitted via the
lm()function. Using the formula interface we can use thesubsetargument to select the data points used to fit the actual model, for example:giving:
As for the double log, you have two choices I guess; i) estimate two separate models as we did above, or ii) estimate via ANCOVA. The log transformation is done in the formula using
log().Via two separate models:
Or via ANCOVA, where we need an indicator variable
You might ask if these two approaches are equivalent? Well they are and we can show this via the model coefficients.
So the two slopes are -0.4306 and -1.4967 for the separate models. The coefficients for the ANCOVA model are:
How do we reconcile the two? Well the way I set up
ind,logm3is parametrised to give more directly values estimated fromlogm2; the intercepts oflogm2andlogm3are the same, as are the coefficients forlog(x). To get the values equivalent to the coefficientsof
logm1, we need to do a manipulation, first for the intercept:where the coefficient for
indTRUEis the difference in the mean of group 1 over the mean of group 2. And for the slope:which is the same as we got for
logm1and is based on the slope for group 2 (coefs[2]) modified by the difference in slope for group 1 (coefs[4]).As for plotting, an easy way is via
abline()for simple models. E.g. for the normal data example:For the log data we might need to be a bit more creative, and the general solution here is to predict over the range of data and plot the predictions:
Which can plot on the original scale, by exponentiating
yhator on the log scale:
For example…
This general solution works well for the more complex ANCOVA model too. Here I create a new pdat as before and add in an indicator
Notice how we get all the predictions we want from the single call to
predict()because of the use of ANCOVA to fitlogm3. We can now plot as before: