clusterMeans: Calculate cluster means

View source: R/clusterMeans.R

clusterMeansR Documentation

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)

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').

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).

Value

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

Author(s)

Simon Grund, Alexander Robitzsch

See Also

within.mitml.list

Examples

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)
})

mitml documentation built on March 31, 2023, 7:01 p.m.