add_grouping {lsmeans} | R Documentation

## Create a grouping factor

### Description

A new factor `G` can be defined having levels based on those of an existing factor `A`. This adds `G` to the reference grid and redefines `A` as being nested in `G`.

### Usage

    add_grouping(object, newname, refname, newlevs)

### Arguments

`object` | A `ref.grid` object
`newname` | Character name of the grouping factor to be created
`refname` | Character name of an existing factor in `object` whose levels are to be grouped
`newlevs` | Character vector or factor of the same length as the levels for `refname`. Each element specifies the corresponding level for `newname`

### Details

This function is useful when one wants to group certain levels of some treatment factor together and summarize by those groups – without fitting a new model. For example, suppose a factor `hosp` refers to five hospitals. A call like `newgrid <- add_grouping(refgrid, "envir", "hosp", c("rural", "urban", "urban", "rural", "urban"))` would add a two-level grouping factor named `envir` in which the first and fourth hospitals are rural and the others are urban. Subsequently, we may use `lsmeans(newgrid, "envir")` to obtain the marginal means for the rural and urban environments.

If `newlevs` is specified as a factor, the user can use its `levels` attribute to control the order in which levels are presented. Otherwise, it will be alphabetical.

### Value

A `ref.grid` object with the factor `newname` added. It will include a nesting structure such that `refname` is nested in `newname`, and with `newname` added to any existing nesting that involves `refname`.

### Note

If `object` already has `refname` nested in some other factors, this creates a conflict and therefore it is not allowed; an error is returned.

### Author(s)

Russell V. Lenth

### See Also

`ref.grid`

### Examples

    require("lsmeans")

    fiber.lm <- lm(strength ~ diameter + machine, data = fiber)
    frg <- ref.grid(fiber.lm)

    ## Suppose the machines are of two types
    gfrg <- add_grouping(frg, newname = "type", refname = "machine",
                         newlevs = c("computerized", "computerized", "manual"))
    gfrg

    lsmeans(gfrg, "type", contr = "pairwise")

[Package lsmeans version 2.27-62 Index]