Learn R Programming

lvmisc (version 0.1.2)

center_variable: Center variable

Description

Center a variable by subtracting the mean from each element. Centering can be performed by the grand mean when by = NULL (the default), or by group means when by is a factor variable.

Usage

center_variable(variable, scale = FALSE, by = NULL)

Value

A numeric vector.

Arguments

variable

A numeric vector.

scale

A logical vector. If scale = TRUE, the centered values of variable are divided by their standard deviation.

by

A vector with the factor class.

Examples

Run this code
df <- data.frame(
  id = 1:20,
  group = as.factor(sample(c("A", "B"), 20, replace = TRUE)),
  body_mass = rnorm(20, mean = 65, sd = 12)
)

df$body_mass_centered <- center_variable(df$body_mass, by = df$group)
df

Run the code above in your browser using DataLab