Learn R Programming

emmeans (version 1.7.0)

add_grouping: Add a grouping factor

Description

This function adds a grouping factor to an existing reference grid or other emmGrid object, such that the levels of one or more existing factors (call them the reference factors) are mapped to a smaller number of levels of the new grouping factor. The reference factors are then nested in the new grouping factor. This facilitates obtaining marginal means of the grouping factor, and contrasts thereof.

Usage

add_grouping(object, newname, refname, newlevs)

Arguments

object

An emmGrid object

newname

Character name of grouping factor to add (different from any existing factor in the grid)

refname

Character name(s) of the reference factor(s)

newlevs

Character vector or factor of the same length as that of the (combined) levels for refname. The grouping factor newname will have the unique values of newlevs as its levels. The order of levels in newlevs is the same as the order of the level combinations produced by expand.grid applied to the levels of refname -- that is, the first factor's levels change the fastest and the last one's vary the slowest.

Value

A revised emmGrid object having an additional factor named newname, and a new nesting structure with each refname %in% newname

Examples

Run this code
# NOT RUN {
fiber.lm <- lm(strength ~ diameter + machine, data = fiber)
( frg <- ref_grid(fiber.lm) )

# Suppose the machines are two different brands
brands <- factor(c("FiberPro", "FiberPro", "Acme"), levels = c("FiberPro", "Acme"))
( gfrg <- add_grouping(frg, "brand", "machine", brands) )

emmeans(gfrg, "machine")

emmeans(gfrg, "brand")

### More than one reference factor
warp.lm <- lm(breaks ~ wool * tension, data = warpbreaks)
gwrg <- add_grouping(ref_grid(warp.lm), 
    "prod",  c("tension", "wool"),  c(2, 1, 1,  1, 2, 1))
        # level combinations:         LA MA HA  LB MB HB

emmeans(gwrg, ~ wool * tension)   # some NAs due to impossible combinations

emmeans(gwrg, "prod")

# }

Run the code above in your browser using DataLab