top of page

From: Bayesian Models for Astrophysical Data, Cambridge Univ. Press

(c) 2017,  Joseph M. Hilbe, Rafael S. de Souza and Emille E. O. Ishida

you are kindly asked to include the complete citation if you used this material in a publication

Code 3.1 Basic linear model in R.
==================================================
# Data
set.seed(1056)                                      # set seed to replicate example
nobs = 250                                           # number of obs in model
x1 <- runif(nobs)                                 # random uniform variable
alpha = 2                                              # intercept
beta = 3                                                # angular coefficient
xb <- alpha + beta* x1                        # linear predictor, xb
y <- rnorm(nobs, xb, sd=1)                 # create y as adjusted random normal variate

# Fit
summary(mod <- lm(y ~ x1))              # model of the synthetic data.

# Output

ypred <- predict(mod, type="response")                            # prediction from the model
plot(x1, y, pch=19,col="red")                                             # plot scatter
lines(x1,ypred,col='grey40',lwd=2)                                    # plot regression line
segments(x1, fitted(mod), x1, y, lwd=1, col="gray70")     # add the residuals
==================================================

Output on screen:

Call:

lm(formula = y ~ x1)

Residuals:

Min             1Q     Median           3Q         Max

-3.2599     -0.7708     -0.0026     0.7888     3.9575

Coefficients:

Estimate Std.        Error        t value           Pr(>|t|)

(Intercept)      1.9885             0.1379          14.42           <2e-16     ***

x1                   2.8935             0.2381          12.15           <2e-16     ***

---

Signif. codes:    0    ‘***’    0.001    ‘**’    0.01    ‘*’    0.05    ‘.’   0.1    ‘ ’    1

Residual standard error:    1.068    on    248    degrees    of    freedom

Multiple R-squared:    0.3732,               Adjusted R-squared:      0.3707

F-statistic:       147.7     on     1     and     248     DF,     p-value:    <     2.2e-16 bottom of page