proc_glm: Calculates a General Linear Model

View source: R/proc_glm.R

proc_glmR Documentation

Calculates a General Linear Model

Description

The proc_glm function performs a general linear model analysis for one or more models. Unlike proc_reg, the proc_glm function accepts categorical predictors through the class parameter, and produces Type I, Type II, and Type III sums of squares. The model(s) are passed on the model parameter, and the input dataset is passed on the data parameter. The by parameter allows you to subset the data into groups and run the model on each group. The weight parameter lets you assign a weight to each observation. The output and options parameters provide additional customization of the results. The proc_glm function currently does not generate plots.

Usage

proc_glm(
  data,
  model,
  class = NULL,
  order = NULL,
  by = NULL,
  stats = NULL,
  output = NULL,
  weight = NULL,
  lsmeans = NULL,
  contrast = NULL,
  estimate = NULL,
  random = NULL,
  options = NULL,
  titles = NULL,
  where = NULL
)

Arguments

data

The input data frame for which to perform the analysis. This parameter is required.

model

A model for the analysis. The model can be specified using either R syntax (y ~ a + b + a:b) or SAS syntax ("y = a b a*b"). To pass multiple models, use a list (R syntax) or a vector of strings (SAS syntax). By default, models are named "MODEL1", "MODEL2", etc.

class

An optional vector of variable names to treat as categorical (factor) predictors. These variables will be converted to factors prior to fitting the model. Pass quoted, or unquoted using the v function.

order

Controls the sort order of the class variable levels. Valid values are "internal", "formatted", "data", and "freq", matching the order parameter on proc_freq and proc_ttest. The default "internal" uses the natural order of the values: character values sort alphabetically, numeric values sort by value, and an existing factor keeps its level order. "formatted" applies the variable's format and uses the order defined by the format. "data" uses order of appearance, and "freq" sorts by descending frequency. Pass one keyword per class variable, or a single keyword to apply to all of them.

Note that for proc_glm the level order is not merely cosmetic. The last level of a class variable is the reference level, so order changes the Type III and "solution" results. It also determines how contrast and estimate coefficients are mapped onto levels: the coefficients are read in level order, so the same coefficient vector means different things under different order values.

The "formatted" keyword goes further still. If the format maps several values onto one label, those values become a single level, and the model loses the degrees of freedom that separated them. This matches the SAS practice of using a format to group a class variable, but it means order = "formatted" can change the model and not just its presentation. Only a user-defined format created with value carries a level order, so that is the only kind of format "formatted" accepts.

by

An optional by group. If specified, the input data will be subset on the by variable(s) prior to performing the analysis.

stats

Optional statistics keywords, corresponding to the options on the "model" statement in SAS. Valid values are "ss1", "ss2", "ss3", "solution", "est", "clparm", "p", "clm", "cli", "noint", "xpx", "inverse", and "e1", "e2", and "e3". See the "Statistics Keywords" section for an explanation of these options.

output

Whether or not to return datasets from the function. Valid values are "out", "none", and "report", plus the data shaping keywords "long", "stacked", and "wide". Default is "out".

weight

The name of a variable to use as a weight for each observation.

lsmeans

The name of one or more class variables for which to compute least-squares means. Each requested effect produces a least-squares means table on the interactive report. The effect(s) must also appear on the class parameter.

contrast

A named list of contrast specifications. Each element name is the contrast label, and each value is itself a named list mapping a model effect to its coefficients over that effect's levels, in level order. For example, contrast = list("F vs M" = list(Sex = c(1, -1))) mirrors the SAS statement contrast 'F vs M' Sex 1 -1. Each contrast produces an F-test row on the interactive report.

Give an effect a matrix instead of a vector to reproduce the comma syntax of a SAS CONTRAST statement: each row of the matrix is one row of the contrast, and the result is a single test whose degrees of freedom equal the number of linearly independent rows. So list("Any diff" = list(AgeGroup = rbind(c(-1, 0, 1), c(0, -1, 1)))) is the SAS statement contrast 'Any diff' AgeGroup -1 0 1, AgeGroup 0 -1 1;.

Interactions may be spelled either way: the SAS operator "a*b" is accepted and normalized to the R operator "a:b". Any effect not named gets a coefficient of zero, as does the intercept. A contrast that is not estimable is dropped with a warning rather than reported.

estimate

A named list of estimate specifications, using the same structure as the contrast parameter. Each estimate produces a row on the interactive report with the estimate, standard error, t value, p value, and confidence limits. Unlike contrast, estimate accepts only single-row specifications, since it estimates one linear combination.

random

The name of one or more class variables to treat as random effects. Produces a table of Type III expected mean squares on the interactive report. The effect(s) must also appear on the class parameter.

options

A vector of optional keywords. Valid values are "alpha =", "noprint", "outstat". The "outstat" option requests an output dataset of the model sums of squares. This is the default output dataset, so the option does not normally need to be passed.

titles

A vector of one or more titles to use for the report output.

where

An expression to filter the rows before statistics are calculated. Use the expression function.

Details

The proc_glm function is a general-purpose linear modeling function built on top of the GLM function from the sasLM package. It produces a dataset output by default, and, when working in RStudio, also produces an interactive report. Statistical output is designed to match SAS.

A model may be specified using R model syntax or SAS model syntax. To use SAS syntax, the model statement must be quoted. To pass multiple models using R syntax, pass them to the model parameter in a list. To pass multiple models using SAS syntax, pass them to the model parameter as a vector of strings.

Value

Normally the requested statistics are shown interactively in the viewer, and output results are returned as a data frame. If "report" datasets are requested they are returned as a list.

Interactive Output

By default, proc_glm results will be sent to the viewer as an HTML report. This functionality makes it easy to get a quick analysis of your data. To turn off the interactive report, pass the "noprint" keyword to the options parameter.

The titles parameter allows you to set one or more titles for your report. Pass these titles as a vector of strings.

The exact datasets used for the interactive report can be returned as a list. To return these datasets, pass the "report" keyword on the output parameter. This list may in turn be passed to proc_print to write the report to a file.

Dataset Output

Dataset results are also returned from the function by default. proc_glm typically returns a single dataset.

The default output dataset is optimized for data manipulation. The column names have been standardized, and additional variables may be present to help with data manipulation. The data values in the output dataset are intentionally not rounded or formatted to give you the most accurate numeric results.

You may also request to return the datasets used in the interactive report. To request these datasets, pass the "report" option to the output parameter. Each report dataset will be named according to the category of statistical results. There are six standard categories: "NObs", "ANOVA", "FitStatistics", "TypeI", "TypeIII", and "ParameterEstimates". Statistics options may generate additional tables in the interactive report.

If you don't want any datasets returned, pass the "none" option on the output parameter.

Statistics Keywords

The following statistics keywords can be passed on the stats parameter. You may pass statistic keywords as a quoted vector of strings, or an unquoted vector using the v() function. An individual statistics keyword can be passed without quoting.

  • solution: Adds a parameter estimates table to the interactive report. "est" is an accepted alias.

  • clparm: Adds confidence limits for the parameter estimates, using the alpha value from the options parameter.

  • p: Adds predicted values and residuals to the interactive report.

  • clm: Adds the standard error and confidence limits of the mean predicted value to the predicted values table. Implies "p".

  • cli: Adds confidence limits for an individual predicted value to the predicted values table. These are wider than the "clm" limits because they include the error variance. Implies "p".

  • noint: Fits the model without an intercept. Every downstream statistic reflects this, and the total sum of squares is no longer corrected for the mean.

  • xpx: Adds the augmented X'X crossproducts matrix, which carries the dependent variable as an extra row and column.

  • inverse: Adds the generalized inverse of the augmented X'X matrix. Its bottom right cell is the error sum of squares.

  • e1, e2, e3: Add the Type I, Type II and Type III estimable function tables.

  • ss1, ss2, ss3: Select which sums of squares to produce. The default is Type I and Type III, as in SAS.

Options

The proc_glm function recognizes the following options. Options may be passed as a quoted vector of strings, or an unquoted vector using the v() function.

  • alpha = : The "alpha = " option will set the alpha value for confidence limit statistics. Set the alpha as a decimal value between 0 and 1. For example, you can set a 90% confidence limit as alpha = 0.1.

  • noprint: Whether to print the interactive report to the viewer. By default, the report is printed to the viewer. The "noprint" option will inhibit printing. You may inhibit printing globally by setting the package print option to false: options("procs.print" = FALSE).

  • outstat: The "outstat" option is used to request the TypeI and TypeIII model sum of squares, F, and P values be sent to the output dataset. The "outstat" dataset is the default output dataset, and this option does not normally need to be passed.

Data Shaping

The output datasets produced by the function can be shaped in different ways. These shaping options allow you to decide whether the data should be returned long and skinny, or short and wide. The shaping options can reduce the amount of data manipulation necessary to get the data into the desired form. The shaping options are as follows:

  • long: Transposes the output datasets so that statistics are in rows and variables are in columns.

  • stacked: Requests that output datasets be returned in "stacked" form, such that both statistics and variables are in rows.

  • wide: Requests that output datasets be returned in "wide" form, such that statistics are across the top in columns, and variables are in rows. This shaping option is the default.

These shaping options are passed on the output parameter. For example, to return the data in "long" form, use output = "long".

See Also

proc_reg()

Examples

# Turn off printing for CRAN checks
options("procs.print" = FALSE)

# Example 1: Basic model
res1 <- proc_glm(mtcars, mpg ~ hp + wt)

# View results
res1
#    MODEL DEPVAR SOURCE  TYPE DF        SS     MEANSQ      FVAL        PROBF
# 1 MODEL1    mpg  ERROR ERROR 29 195.04775   6.725785        NA           NA
# 2 MODEL1    mpg     hp   SS1  1 678.37287 678.372874 100.86152 5.987344e-11
# 3 MODEL1    mpg     wt   SS1  1 252.62656 252.626559  37.56091 1.119647e-06
# 4 MODEL1    mpg     hp   SS3  1  83.27418  83.274183  12.38133 1.451229e-03
# 5 MODEL1    mpg     wt   SS3  1 252.62656 252.626559  37.56091 1.119647e-06

# Example 2: Report output
res2 <- proc_glm(mtcars, mpg ~ hp + wt,
                 output = "report")

# View results
res2
# $NObs
#                         LABEL NOBS
# 1 Number of Observations Read   32
# 2 Number of Observations Used   32
#
# $ANOVA
#            SOURCE DF     SUMSQ     MEANSQ     FVAL        PROBF
# 1           Model  2  930.9994 465.499716 69.21121 9.109047e-12
# 2           Error 29  195.0478   6.725785       NA           NA
# 3 Corrected Total 31 1126.0472         NA       NA           NA
#
# $FitStatistics
#         RSQ  COEFVAR     RMSE  DEPMEAN
# 1 0.8267855 12.90857 2.593412 20.09062
#
# $TypeI
#   SOURCE DF    SUMSQ   MEANSQ      FVAL        PROBF
# 1     hp  1 678.3729 678.3729 100.86152 5.987344e-11
# 2     wt  1 252.6266 252.6266  37.56091 1.119647e-06
#
# $TypeIII
#   SOURCE DF     SUMSQ    MEANSQ     FVAL        PROBF
# 1     hp  1  83.27418  83.27418 12.38133 1.451229e-03
# 2     wt  1 252.62656 252.62656 37.56091 1.119647e-06
#
# $ParameterEstimates
#        PARM         EST     STDERR         T        PROBT
# 1 Intercept 37.22727012 1.59878754 23.284689 0.000000e+00
# 2        hp -0.03177295 0.00902971 -3.518712 1.451229e-03
# 3        wt -3.87783074 0.63273349 -6.128695 1.119647e-06

#'
# Example 3: By variable
res3 <- proc_glm(mtcars, mpg ~ hp + wt,
                 by = cyl)

# View results
res3
#    BY  MODEL DEPVAR SOURCE  TYPE DF         SS     MEANSQ       FVAL      PROBF
# 1   4 MODEL1    mpg  ERROR ERROR  8 64.9396474  8.1174559         NA         NA
# 2   4 MODEL1    mpg     hp   SS1  1 55.7389699 55.7389699  6.8665565 0.03063088
# 3   4 MODEL1    mpg     wt   SS1  1 82.7068372 82.7068372 10.1887633 0.01276524
# 4   4 MODEL1    mpg     hp   SS3  1 34.9973354 34.9973354  4.3113675 0.07151610
# 5   4 MODEL1    mpg     wt   SS3  1 82.7068372 82.7068372 10.1887633 0.01276524
# 6   6 MODEL1    mpg  ERROR ERROR  4  5.2112707  1.3028177         NA         NA
# 7   6 MODEL1    mpg     hp   SS1  1  0.2046882  0.2046882  0.1571119 0.71206529
# 8   6 MODEL1    mpg     wt   SS1  1  7.2611839  7.2611839  5.5734459 0.07759393
# 9   6 MODEL1    mpg     hp   SS3  1  1.5772106  1.5772106  1.2106150 0.33297540
# 10  6 MODEL1    mpg     wt   SS3  1  7.2611839  7.2611839  5.5734459 0.07759393
# 11  8 MODEL1    mpg  ERROR ERROR 11 42.8497010  3.8954274         NA         NA
# 12  8 MODEL1    mpg     hp   SS1  1  6.8542713  6.8542713  1.7595685 0.21155901
# 13  8 MODEL1    mpg     wt   SS1  1 35.4960277 35.4960277  9.1122294 0.01168393
# 14  8 MODEL1    mpg     hp   SS3  1  6.3136353  6.3136353  1.6207812 0.22923028
# 15  8 MODEL1    mpg     wt   SS3  1 35.4960277 35.4960277  9.1122294 0.01168393

# Example 4: Long output
res4 <- proc_glm(mtcars, mpg ~ hp + wt,
                 output = "long")

# View results
res4
#     MODEL DEPVAR SOURCE  TYPE   STAT         COL1
# 1  MODEL1    mpg  ERROR ERROR     DF 2.900000e+01
# 2  MODEL1    mpg  ERROR ERROR     SS 1.950478e+02
# 3  MODEL1    mpg  ERROR ERROR MEANSQ 6.725785e+00
# 4  MODEL1    mpg  ERROR ERROR   FVAL           NA
# 5  MODEL1    mpg  ERROR ERROR  PROBF           NA
# 6  MODEL1    mpg     hp   SS1     DF 1.000000e+00
# 7  MODEL1    mpg     hp   SS1     SS 6.783729e+02
# 8  MODEL1    mpg     hp   SS1 MEANSQ 6.783729e+02
# 9  MODEL1    mpg     hp   SS1   FVAL 1.008615e+02
# 10 MODEL1    mpg     hp   SS1  PROBF 5.987344e-11
# 11 MODEL1    mpg     wt   SS1     DF 1.000000e+00
# 12 MODEL1    mpg     wt   SS1     SS 2.526266e+02
# 13 MODEL1    mpg     wt   SS1 MEANSQ 2.526266e+02
# 14 MODEL1    mpg     wt   SS1   FVAL 3.756091e+01
# 15 MODEL1    mpg     wt   SS1  PROBF 1.119647e-06
# 16 MODEL1    mpg     hp   SS3     DF 1.000000e+00
# 17 MODEL1    mpg     hp   SS3     SS 8.327418e+01
# 18 MODEL1    mpg     hp   SS3 MEANSQ 8.327418e+01
# 19 MODEL1    mpg     hp   SS3   FVAL 1.238133e+01
# 20 MODEL1    mpg     hp   SS3  PROBF 1.451229e-03
# 21 MODEL1    mpg     wt   SS3     DF 1.000000e+00
# 22 MODEL1    mpg     wt   SS3     SS 2.526266e+02
# 23 MODEL1    mpg     wt   SS3 MEANSQ 2.526266e+02
# 24 MODEL1    mpg     wt   SS3   FVAL 3.756091e+01
# 25 MODEL1    mpg     wt   SS3  PROBF 1.119647e-06

procs documentation built on Nov. 2, 2026, 5:06 p.m.