Learn R Programming

mariposa (version 0.7.3)

linear_regression: Run a Linear Regression

Description

linear_regression() performs bivariate or multiple linear regression with SPSS-compatible output. Wraps stats::lm() and adds standardized coefficients (Beta), a formatted ANOVA table, and a model summary matching SPSS REGRESSION output.

Supports two interface styles:

  • Formula interface: linear_regression(data, life_satisfaction ~ age + education)

  • SPSS-style: linear_regression(data, dependent = life_satisfaction, predictors = c(age, education))

Usage

linear_regression(
  data,
  formula = NULL,
  dependent = NULL,
  predictors = NULL,
  weights = NULL,
  use = c("listwise", "pairwise"),
  standardized = TRUE,
  conf.level = 0.95,
  factors = c("dummy", "numeric")
)

Value

For ungrouped + listwise data, an object of class c("linear_regression", "lm") — the fitted lm itself, with mariposa-specific slots attached:

coef_table

SPSS-style tibble with B, Std.Error, Beta, t, p, CI_lower, CI_upper. For weighted models, SE / t / p are adjusted to SPSS's frequency-weight df (see Technical Details).

anova_table

SPSS-style overall-model ANOVA tibble (Source × Sum_of_Squares / df / Mean_Square / F_statistic / Sig).

model_summary

List with R, R_squared, adj_R_squared, std_error.

descriptives

Tibble with Mean, Std.Deviation, N for all variables.

n

Sample size (listwise complete cases; weighted N when weighted).

formula, dependent, predictor_names, weighted, weight_name, use, is_grouped, standardized, conf.level

Call metadata.

Because the object inherits from "lm", all standard generics (predict(), anova(), vcov(), confint(), residuals(), fitted(), coef(), model.matrix(), broom::tidy(), broom::glance(), broom::augment()) dispatch natively without unwrapping. summary() returns the SPSS-style mariposa summary; for the raw lm summary use stats::summary.lm() on the same object.

For use = "pairwise" (no single fitted lm available) or for grouped data, returns a list of class "linear_regression". Pairwise results expose the same SPSS-style tables but not the lm generics; grouped results hold one fitted lm-inheriting model per group under $groups.

Arguments

data

Your survey data (a data frame or tibble). If grouped (via dplyr::group_by()), separate regressions are run for each group.

formula

A formula specifying the model (e.g., y ~ x1 + x2). If provided, dependent and predictors are ignored.

dependent

The dependent variable (unquoted). Used with predictors when no formula is given.

predictors

Predictor variable(s) (unquoted, supports tidyselect). Used with dependent when no formula is given.

weights

Optional survey weights (unquoted variable name). When specified, weighted least squares (WLS) is used, matching SPSS WEIGHT BY.

use

How to handle missing data: "listwise" (default) drops any case with a missing value on any variable (matching SPSS /MISSING LISTWISE). "pairwise" computes the regression from a pairwise covariance/correlation matrix, retaining more cases (matching SPSS /MISSING PAIRWISE).

standardized

Logical. If TRUE (default), standardized coefficients (Beta) are calculated and included in the output.

conf.level

Confidence level for coefficient intervals (default 0.95).

factors

How factor predictors are entered into the model: "dummy" (default, matches base R lm()) expands a factor with L levels into L - 1 contrasts; "numeric" silently coerces factor levels to their integer codes, matching SPSS REGRESSION default behavior (ordinal-as-scale). The "numeric" mode emits a one-line cli::cli_inform() listing the coerced variables. The "numeric" mode is required to reproduce SPSS results when factor predictors carry ordered meaning (e.g., 4-level education). Note that for ordered factors, "dummy" applies R's default polynomial contrasts (terms suffixed .L, .Q, .C), not treatment dummies; convert with factor(x, ordered = FALSE) first if you want dummy coding.

Details

Understanding the Results

The output includes four sections matching SPSS REGRESSION output:

  • Model Summary: R, R-squared, Adjusted R-squared, and Standard Error of the Estimate. R-squared tells you how much variance in the dependent variable is explained by the predictors.

  • ANOVA: Tests whether the overall model is significant. A significant F-test means at least one predictor matters.

  • Coefficients: B (unstandardized), Beta (standardized), t-value, p-value, and confidence intervals for each predictor.

  • Descriptives: Mean, SD, and N for all variables in the model.

Interpreting coefficients:

  • B (unstandardized): For each 1-unit increase in the predictor, the dependent variable changes by B units

  • Beta (standardized): Allows comparison across predictors with different scales. Larger absolute Beta = stronger effect

  • p-value: Values below 0.05 indicate statistically significant predictors

When to Use This

Use linear_regression() when:

  • Your dependent variable is continuous (e.g., income, satisfaction score)

  • You want to predict an outcome from one or more predictors

  • You need standardized coefficients to compare predictor importance

For binary outcomes (yes/no, 0/1), use logistic_regression instead.

Technical Details

Missing Data: By default, listwise deletion is used (matching SPSS REGRESSION /MISSING LISTWISE). Set use = "pairwise" to match SPSS /MISSING PAIRWISE, which computes the regression from a pairwise covariance matrix. Pairwise deletion retains more cases and produces results closer to SPSS output when data has varying patterns of missingness.

Weights: When weights are specified, they are treated as frequency weights (matching SPSS WEIGHT BY behavior). The model is fitted using weighted least squares via lm(weights = ...).

Standardized Coefficients: Beta = B * (SD_x / SD_y). This matches the SPSS standardized coefficient output. Not available for the intercept. For dummy-coded factor terms (factors = "dummy"), the SD of the contrast column from the design matrix is used.

Factor Predictors: By default (factors = "dummy"), factor predictors are expanded into L - 1 contrasts via R's stats::model.matrix(), matching base R lm(): unordered factors get treatment (dummy) contrasts against the first level, while ordered factors get R's default polynomial contrasts (.L/.Q/.C terms). Pass factors = "numeric" to silently coerce factor levels to their integer codes (SPSS REGRESSION default). The "numeric" mode is required to reproduce SPSS results for ordinal predictors like education or Likert scales that SPSS treats as continuous.

Grouped Analysis: When data is grouped via dplyr::group_by(), a separate regression is run for each group (matching SPSS SPLIT FILE BY).

See Also

logistic_regression for binary outcome variables.

describe for checking variable distributions before regression.

pearson_cor for checking bivariate correlations.

summary.linear_regression for detailed output with toggleable sections.

Other regression: logistic_regression(), marginal_effects()

Examples

Run this code
library(dplyr)
data(survey_data)

# Bivariate regression
linear_regression(survey_data, life_satisfaction ~ age)

# Multiple regression
linear_regression(survey_data, income ~ age + education + life_satisfaction)

# SPSS-style interface
linear_regression(survey_data,
                  dependent = life_satisfaction,
                  predictors = c(trust_government, trust_media, trust_science))

# Weighted regression
linear_regression(survey_data, life_satisfaction ~ age, weights = sampling_weight)

# Grouped by region
survey_data |>
  dplyr::group_by(region) |>
  linear_regression(life_satisfaction ~ age)

# Factor predictors: dummy-coding (default, matches base R lm())
linear_regression(survey_data, income ~ age + education)

# Factor predictors: SPSS-style ordinal-as-scale
linear_regression(survey_data, income ~ age + education,
                  factors = "numeric")

# --- Three-layer output ---
result <- linear_regression(survey_data, life_satisfaction ~ age + income)
result                                  # compact one-line overview
summary(result)                         # full detailed SPSS-style output
summary(result, descriptives = FALSE)   # hide descriptives section

Run the code above in your browser using DataLab