4.8 Summary of important R code

The main components of R code used in this chapter follow with components to modify in lighter and/or ALL CAPS text, remembering that any R packages mentioned need to be installed and loaded for this code to have a chance of working:

  • tally(A~B, data=DATASETNAME)

    • Requires the mosaic package be loaded.

    • Provides the counts of observations in each combination of categorical predictor variables A and B, used to check for balance and understand sample sizes in each combination.

  • DATASETNAME$VARIABLENAME <- factor(DATASETNAME$VARIABLENAME)

    • Use the factor function on any numerically coded explanatory variable where the numerical codes represent levels of a categorical variable.
  • intplot(Y~A*B, data=DATASETNAME)

    • Download and install using:

      source("http://www.math.montana.edu/courses/s217/documents/intplotfunctions_v2.R")

    • Provides interaction plot.

  • intplotarray(Y~A*B, data=DATASETNAME)

    • Download and install using:

      source("http://www.math.montana.edu/courses/s217/documents/intplotfunctions_v2.R")

    • Provides interaction plot array that makes interaction plots switching explanatory variable roles and makes pirate-plots of the main effects.

  • INTERACTIONMODELNAME <- lm(Y~A*B, data=DATASETNAME)

    • Fits the interaction model with main effects for A and B and an interaction between them.

    • This is the first model that should be fit in Two-Way ANOVA modeling situations.

  • ADDITIVEMODELNAME <- lm(Y~A+B, data=DATASETNAME)

    • Fits the additive model with only main effects for A and B but no interaction between them.

    • Should only be used if the interaction has been decided to be unimportant using a test for the interaction.

  • summary(MODELNAME)

    • Generates model summary information including the estimated model coefficients, SEs, t-tests, and p-values.
  • Anova(MODELNAME)

    • Requires the car package to be loaded.

    • Generates a Type II Sums of Squares ANOVA table that is useful for both additive and interaction models, but it is most important to use when working with the additive model as it provides inferences for each term conditional on the other one.

  • par(mfrow=c(2,2)); plot(MODELNAME)

    • Generates four diagnostic plots including the Residuals vs Fitted and Normal Q-Q plot.
  • plot(allEffects(MODELNAME))

    • Requires the effects package be loaded.

    • Plots the results from the estimated model.

  • plot(allEffects(MODELNAME, residuals = T))

    • Plots the results from the estimated model with partial residuals.