I plotted a simple linear regression in ggplot both for the entire data and training set and test set. But, the problem is that it just provides a plot, nothing more like RMSE, R2, etc. How can I compare? How can I measure the performance of my simple linear regression prediction model?
2 Answers
ggplot2
is one of the most popular alternatives for producing plots in R. As George Savva has pointed out, computing statistics in R does not need ggplot2
nor should the latter be preferably used for that.
The following example shows how to compute a simple linear OLS regression and how to gain $R^2$ and RMSE (and additionally AIC and BIC even though you did not ask for those two):
#some example data
x <- c(0,1,2,3,4.5,4.6,7)
y <- c(.1, 2.1, 3.2, 4.3, 4.0, 6,7)
linear.model <- lm(y ~ x)
summary(linear.model)
# find R^2
summary(linear.model)$r.squared
# RSME is the square root of the mean of squared residuals
sqrt(mean(linear.model$residuals^2))
# Akaike Information Criterion
AIC(linear.model)
# so-called BIC or SBC (Schwarz's Bayesian criterion).
BIC(linear.model)
Estimating and inspecting a linear model in R is described in chapter 11 of the R manual here: cran.r-project.org/doc/manuals/r-release/R-intro.pdf. If you are using R for statistical modelling you should read this.
In short though, the function to estimate linear models is lm()
. Once you have estimated your model the summary()
function will report R-squared, residual error, etc. ggplot is for plotting, not for model building and diagnostics.
lm()
is the function for estimating linear models.ggplot
just provides a quick fit for visual inspection. Chapter 11 covers statistical modelling cran.r-project.org/doc/manuals/r-release/R-intro.pdf $\endgroup$summary
to extract R-quared from thelm
model... $\endgroup$