Simulating Linear Regression Models

Simulating Linear Regression Models in R

Explore practical answers to key questions on simulating linear regression models, controlling predictor correlation, adjusting effect strength, and ensuring reproducibility.

Q1: Why should I simulate linear regression models instead of using real-world data?

Simulating data creates a dataset with a known “ground truth” where you explicitly set the true values of the intercept ($\beta_0$), slope ($\beta_1$), and residual standard deviation ($\sigma$). This allows you to:

  • Validate custom analysis scripts or new package algorithms to ensure they recover the true parameters.
  • Perform statistical power calculations and sample size estimates.
  • Stress-test linear model assumptions (e.g., non-normality, heteroscedasticity) to evaluate model robustness.

Q2: How do I ensure my simulated linear model results are reproducible?

Always set a random seed before running pseudorandom generation functions like rnorm() or rbinom(). Using set.seed(123) (a fixed seed, or any integer) ensures that R generates the exact same sequence of random numbers every time the code is executed.

Q3: How do I simulate a linear regression model with multiple predictors?

To extend a simple linear regression model to multiple predictors, generate additional independent variables and add their weighted terms to the formula for $y$:

n <- 100

x1 <- rnorm(n, mean = 0, sd = 1) # Continuous predictor
x2 <- rbinom(n, size = 1, prob = 0.5) # Binary predictor
e <- rnorm(n, mean = 0, sd = 2) # Noise

b0 <- 0.5; b1 <- 2; b2 <- -1.5
y <- b0 + (b1 * x1) + (b2 * x2) + e

sim_model_multi <- lm(y ~ x1 + x2)
summary(sim_model_multi)

Q4: Why do not the estimated parameters (lm()) exactly match my defined $\beta_0$ and $\beta_1$ values?

The estimates generated by lm() differ slightly from your target parameters due to random sampling variance introduced by the error term ($e$). As sample size ($N$) increases, the estimated coefficients converge toward the true parameters according to the Law of Large Numbers.

Q5: How can I change the strength of the relationship between $x$ and $y$ in my simulation?

You can adjust the strength of the relationship ($R^2$) in two ways:

  • Increase/ Decrease $\beta_1$: Larger absolute values of $\beta_1$ increase the signal relative to the noise.
  • Adjust Error Variance ($\sigma$): Lowering the standard deviation in rnorm(n, 0, sd) reduces residual variance, resulting in higher $R^2$ values and tighter clustering around the regression line.

Q6: How do I simulate a linear model with correlated predictors (multicollinearity)?

To simulate correlated continuous predictors, use the mvrnorm() function from the MASS package to draw samples from a multivariate normal distribution with a defined covariance matrix:

library(MASS)

set.seed(123)
n <- 100

# Define means and covariance matrix (rho = 0.7 correlation)

mu <- c(0, 0)
Sigma <- matrix(c(1, 0.7, 0.7, 1), ncol = 2)

# Generate correlated predictors x1 and x2

X <- mvrnorm(n, mu = mu, Sigma = Sigma)
x1 <- X[, 1]
x2 <- X[, 2]

e <- rnorm(n, mean = 0, sd = 2)
y <- 0.5 + 2*x1 + 1.5*x2 + e

Q7: What is the importance of simulating linear regression models in R?

Simulating linear regression models in R is a foundational practice in statistics, data science, and quantitative research. Instead of analyzing empirical data (where the true underlying process is unknown), simulation allows you to create data with known parameters ($\beta$ coefficients, noise level, distribution shapes) and evaluate how well statistical methods perform.

Core Benefits of Simulating Linear Regression Models in R

  1. Validating Methodologies and R Code:
    By defining exact theoretical parameters (e.g., setting $\ intercept = 2$, $\beta_1 = 3.5$, and $\sigma = 1$), you know the “ground truth.” Fitting lm() on this simulated data lets you verify that your analysis pipeline correctly recovers those parameters and that your scripts are bug-free before applying them to real, messy data.
  2. Conducting Power Analysis and Sample Size Estimation:
    Standard power formulas often fail when study designs involve non-standard noise distributions, missing data, or complex predictor structures. By repeatedly simulating datasets across varying sample sizes ($N$) and effect sizes, you can empirically calculate statistical power (the proportion of simulations where $p < 0.05$) to determine the exact sample size needed for a study.
  3. Evaluating Model Assumptions and Robustness:
    Linear regression relies on key assumptions: linearity, independence, homoscedasticity, and normality of residuals. Simulation lets you systematically violate these assumptions, such as injecting heteroscedastic error or heavy-tailed noise, to observe how severely standard errors, $p$-values, and confidence intervals are degraded.
  4. Understanding the Impact of Multicollinearity:
    By using packages like MASS (with mvrnorm()) to generate correlated predictors, one can observe firsthand how high correlation between variables inflates standard errors and makes individual $\beta$ estimates unstable without altering the overall model $R^2$.
  5. Exploring Finite-Sample vs. Asymptotic Behavior:
    Simulation demonstrates Central Limit Theorem principles in real time. You can show how parameter estimates ($\hat{\beta}$) fluctuate widely in small samples ($N = 15$) but consistently converge toward the true parameters as sample sizes grow ($N = 1000$).
rfaqs.com simulating linear regression models in r

Simulating a Linear Regression Model in R

Simulating Linear Regression Model in R

Understanding linear regression begins with understanding how data is generated. While estimating models from real-world datasets is standard practice, simulating data lets you control the ground truth, making it an invaluable tool for testing statistical methods, understanding model assumptions, and validating analytical workflows.

In this post, I will cover the mathematical foundation of linear regression, how to simulate a model with both continuous and binary predictors in R language, real-world applications, and better ways to visualize your simulated output.

Simple Linear Regression Model Definition and Mathematics

A simple linear regression model models the relationship between a dependent response variable ($y$) and an independent predictor ($x$):

$$y = \beta_0 + \beta_1 x + \varepsilon$$

where

  • $y$ is the outcome variable.
  • $\beta_0$ is the intercept (the expected value of $y$ when $x = 0$).
  • $\beta_1$ is the slope parameter (the expected change in $y$ for a one-unit change in $x$).
  • $\varepsilon$ is the random error term, assumed to be normally distributed: $\varepsilon \sim N(0, \sigma^2)$.

Data Generating Process Parameters

For our simulation setup:

  • Intercept: $\beta_0 = 0.5$
  • Slope coefficient: $\beta_1 = 2$
  • Error variance: $\sigma^2 = 2^2 = 4$ (Standard deviation $\sigma = 2$)

Simulating Linear Regression Model in R

We will consider two scenarios regarding simulating linear regression model in R language.

Binary Predictor ($x \in {0, 1}$)

In many real-world settings, $x$ represents a binary variable, such as Control vs. Treatment, Male vs. Female, or Unexposed vs. Exposed. The following is the exact code to generate 100 observations where $x$ follows a Bernoulli distribution (Coin flip with $p = 0.5$):

# Set seed for reproducible results
set.seed(123)

# 1. Define sample size and parameters
n  <- 100
b0 <- 0.5
b1 <- 2

# 2. Simulate predictors and error terms
x <- rbinom(n, size = 1, prob = 0.5)  # Binary predictor (0 or 1)
e <- rnorm(n, mean = 0, sd = 2)        # Random error ~ N(0, 2^2)

# 3. Calculate outcome variable
y <- b0 + b1 * x + e

# 4. Verify parameter estimates using linear regression
sim_model <- lm(y ~ x)
summary(sim_model)

When you run summary(sim_model), the estimated intercept and coefficient will be close to $\beta_0 = 0.5$ and $\beta_1 = 2$. Due to random sampling noise from $e$, they would not be exact, but increasing n to $10,000$ will bring estimates infinitely close to the true parameter values (Law of Large Numbers).

Simulating Linear regression model in R

Continuous Predictor ($x \sim N(0, 1^2)$)

If your predictor $x$ is a continuous variable (e.g., age, dose, income), you replace rbinom with rnorm:

set.seed(123)

n  <- 100
b0 <- 0.5
b1 <- 2

# Continuous predictor centered at 0 with SD of 1
x <- rnorm(n, mean = 0, sd = 1)  
e <- rnorm(n, mean = 0, sd = 2)

y <- b0 + b1 * x + e

sim_model_cont <- lm(y ~ x)
summary(sim_model_cont)

Graphical Representation of Simulated Model

Calling plot(y) directly on sequential data creates an index plot, which does not effectively communicate the relationship between $x$ and $y$. Here are clearer ways to visualize simulated models in R:

For a binary predictor, a strip chart with jitter or a boxplot overlaid with data points provides clear insight into group distributions.

# Base R Plot with Jitter
plot(jitter(x, factor = 0.2), y, 
     col = ifelse(x == 1, "#1B9E77", "#D95F02"),
     pch = 19, xlab = "Binary Predictor (x)", ylab = "Outcome (y)",
     main = "Simulated Linear Regression with Binary Predictor",
     xaxt = "n")

axis(1, at = c(0, 1), labels = c("Group 0 (Control)", "Group 1 (Treatment)"))

# Add True Data Generating Line
abline(a = b0, b = b1, col = "black", lty = 2, lwd = 2)

# Add Fitted Regression Line
abline(sim_model, col = "blue", lwd = 2)

legend("topleft", legend = c("True Model", "Fitted Model"),
       col = c("black", "blue"), lty = c(2, 1), lwd = 2)
Graphical representation of linear regression model in R Language
# Enhanced Visualization using ggplot2
library(ggplot2)

sim_data <- data.frame(x = factor(x), y = y)

ggplot(sim_data, aes(x = x, y = y, fill = x)) +
  geom_boxplot(alpha = 0.4, outlier.shape = NA) +
  geom_jitter(width = 0.1, size = 2, alpha = 0.7) +
  stat_summary(fun = mean, geom = "point", shape = 23, size = 4, fill = "red") +
  labs(title = "Simulated Binary Linear Model (N = 100)",
       subtitle = "Red diamonds represent group means (Estimated Intercept & Slope effect)",
       x = "Group (x)",
       y = "Response (y)") +
  theme_minimal() +
  theme(legend.position = "none")

Binomial Distribution in R

Binomial-Probability-Distribution-in-R.

In this post, we will learn about the use and application of the Binomial Distribution in R. The binomial probability distribution is used to model the number of “Successes” in a fixed number of independent trials, where every trial has only two possible outcomes (such as success or failure, true or false, right or wrong, and yes or no, etc.), whereas the probability of success remains constant/ fixed. One can easily analyze the survey responses, exam pass rates, product defects, medical treatment outcomes, and customer conversions in the R language.

What is the Binomial Distribution?

A binomial experiment must satisfy four conditions:

  • The number of trials is fixed and denoted by $n$
  • Each trial has exactly two possible outcomes: success or failure
  • The probability of success ($p$) is the same in every trial
  • The trials are independent (one outcome does not affect the other)

If $X$ is the number of successes in $n$ trials, then

$$X\sim Binomial(n, p)$$

The probability of observing exactly $x$ successes is

$$P(X=x) = \binom{n}{x} p^x(1-p)^{n-x}$$

Real-Life Examples of the Binomial Distribution

SituationSuccessFailure$n$$p$
Tossing a coin 10 timesHeadTail100.50
A student answers 20 multiple-choice questionsCorrect answerIncorrect answer200.25
A factory inspects 50 productsDefective itemNon-defective item500.05
A doctor treats 30 patientsPatient recoversPatient does not recover300.70
An online store records 100 website visitsVisitor purchasesVisitor does not purchase1000.03

For example, suppose a basketball player makes 80% of free throws. If they attempt 10 free throws, the number of successful shots follows a Binomial distribution with $n=10$ and $p=0.80$.

Binomial Distribution in R Language

R provides four main functions for the binomial distribution:

FunctionPurposeExample
dbinom(x, size, prob)Probability of exactly $x$ successesProbability of exactly 7 heads in 10 tosses
pbinom(q, size, prob)Cumulative probability: $P(X\ge q)Probability of at most 7 heads
qbinom(p, size, prob)Quantile: smallest $x$ with cumulative probability at least $p$90th percentile of successes
rbinom(n, size, prob)Generate random binomial valuesSimulate 1,000 experiments

These functions use size for the number of trials $n$ and prob for the probability of success $p$

Coin Tossing Example

Suppose you toss a fair coin 10 times. What is the probability of getting exactly 7 heads?

# Probability of exactly 7 heads in 10 tosses

dbinom(x = 7, size = 10, prob = 0.5)

## Output
[1] 0.1171875

So the probability is approximately 11.72%. To get the probability of getting 7 or fewer heads, one can use

pbinom(q = 7, size = 10, prob = 0.5)

## Output
[1] 0.9453125

There is about a 94.53% chance of getting at most 7 heads.

Student Exam Performance

Imagine a student guesses on 20 multiple-choice questions, each with four options. The probability of guessing correctly is $p=\frac{1}{4}=0.25$. What is the probability that the student answers exactly 8 questions correctly?

dbinom(x = 8, size = 20, prob = 0.25)
## Output
[1] 0.06088669

The probability is only about 6.08%, showing that randomly getting 8 correct answers out of 20 is unlikely.

Graphing the Binomial Distribution in R

The most useful graph is the probability mass function (PMF). Each bar shows the probability of obtaining a particular number of successes.

n <- 10
p <- 0.5
x <- 0:n

probabilities <- dbinom(x, size = n, prob = p)

plot( x,  probabilities,
  type = "h",  lwd = 3, col = "steelblue",
  xlab = "Number of Successes",
  ylab = "Probability",
  main = "Binomial Distribution: n = 10, p = 0.5"
)

points(x, probabilities, pch = 19, col = "steelblue")
Binomial Distribution in R

This creates a symmetric distribution because $p=0.5$. The highest bar occurs at 5 successes, which is also the expected value:

$$E(X) = np = 10\times 0.5 = 5$$

Effect of Changing Probability

The shape of the binomial distribution changes when $p$ changes.

x <- 0:20

par(mfrow = c(1, 3))

plot(x, dbinom(x, size = 20, prob = 0.2),
     type = "h", lwd = 3, col = "tomato",
     main = "p = 0.2",
     xlab = "Successes", ylab = "Probability")

plot(x, dbinom(x, size = 20, prob = 0.5),
     type = "h", lwd = 3, col = "steelblue",
     main = "p = 0.5",
     xlab = "Successes", ylab = "Probability")

plot(x, dbinom(x, size = 20, prob = 0.8),
     type = "h", lwd = 3, col = "seagreen",
     main = "p = 0.8",
     xlab = "Successes", ylab = "Probability")

par(mfrow = c(1, 1))
Effect of Changing Probability on the Shape of Binomial Distribution

From graphical representations of the binomial probability distribution for different probabilities of success, one can see that

  • when $p=0.2$, the distribution is right-skewed
  • when $p=0.5$, the distribution is symmetric
  • when $p=0.8$, the distribution is left-skewed

This is because low success probabilities make a small number of successes more likely, while high success probabilities make a large number of successes more likely.

Simulating Binomial Data in R

Simulation helps students see the binomial distribution in action. The following code simulates 1000 experiments of tossing a fair coin 10 times:

simulated_heads <- rbinom(n = 1000, size = 10, prob = 0.5)

head(simulated_heads)

## Output
[1] 3 5 5 5 3 5

One can visualize the simulated results

hist( simulated_heads,
  breaks = seq(-0.5, 10.5, by = 1),
  col = "lightblue", border = "white",
  main = "Simulated Coin Tosses: 1,000 Experiments",
  xlab = "Number of Heads in 10 Tosses",
  ylab = "Frequency"
)
Simulating Binomial Data in R

The histogram should resemble the theoretical binomial PMF, especially as the number of simulations increases. This demonstrates the connection between probability theory and observed data.

Mean and Variance of Binomial Distribution in R

For a binomial distribution, the mean and variance can be represented as

\begin{align*}
E(X) & = np\\
Var(X) &= np(1-p)
\end{align*}

One can compute the mean and variance of the Binomial Distribution in R as follows:

n <- 10
p <- 0.5

m <- n * p
var <- n * p * (1 - p)

paste("mean=", m)
paste("var=", var)

## Output
[1] "mean= 5"
[1] "var= 2.5"

The binomial probability distribution is one of the most practical probability models in statistics because many real-world situations involve repeated success/ failure trials. R makes it easy to calculate exact probabilities, simulate data, estimate quantiles, and create clear visualizations using dbinom(), pbinom(), qbinom(), and rbinom().