Learn R Programming

mitml (version 0.4-5)

clusterMeans: Calculate cluster means

Description

Calculates the mean of a given variable within each cluster, possibly conditioning on an additional grouping variable.

Usage

clusterMeans(x, cluster, adj = FALSE, group = NULL)

Value

A numeric vector with the same length as x containing the cluster mean for all units.

Arguments

x

A numeric vector for which cluster means should be calculated. Can also be supplied as a character string denoting a variable in the current environment (see 'Details').

cluster

A numeric vector or a factor denoting the cluster membership of each unit in x. Can also be supplied as a character string (see 'Details').

adj

Logical flag indicating if person-adjusted group means should be calculated. If TRUE, cluster means are calculated for each unit by excluding that unit from calculating the cluster mean. Default is FALSE.

group

(optional) A grouping factor or a variable that can be interpreted as such. If specified, cluster means are calculated separately within the sub-groups defined by group. Can also be supplied as a character string (see 'Details').

Author

Simon Grund, Alexander Robitzsch

Details

This function calculates the mean of a variable within each level of a cluster variable. Any NA are omitted during calculation.

The three main arguments of the function can also be supplied as (single) character strings, denoting the name of the respective variables in the current environment. This is especially useful for calculating several cluster means simultaneously, for example using within.mitml.list (see 'Example 2' below).

See Also

within.mitml.list

Examples

Run this code
data(studentratings)

fml <- ReadDis + SES ~ ReadAchiev + (1|ID)
imp <- panImpute(studentratings, formula = fml, n.burn = 1000, n.iter = 100, m = 5)

implist <- mitmlComplete(imp)

# * Example 1: single cluster means

# calculate cluster means (for each data set)
with(implist, clusterMeans(ReadAchiev, ID))

# ... person-adjusted cluster means
with(implist, clusterMeans(ReadAchiev, ID, adj = TRUE))

# ... groupwise cluster means
with(implist, clusterMeans(ReadAchiev, ID, group = Sex))

# * Example 2: automated cluster means using 'for' and 'assign'

# calculate multiple cluster means within multiply imputed data sets
within(implist,{
  vars <- c("ReadAchiev", "MathAchiev", "CognAbility")
  for(i in vars) assign(paste(i, "Mean", sep = "."), clusterMeans(i, ID))
  rm(i, vars)
})

Run the code above in your browser using DataLab