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.

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

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.

Value

A numeric vector.

Examples

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
#> id group body_mass body_mass_centered #> 1 1 B 73.58482 7.9011490 #> 2 2 B 51.93189 -13.7517821 #> 3 3 B 69.81828 4.1346143 #> 4 4 A 69.85134 4.4779158 #> 5 5 B 89.51611 23.8324393 #> 6 6 B 78.66696 12.9832899 #> 7 7 A 55.67533 -9.6980863 #> 8 8 A 61.63453 -3.7388853 #> 9 9 A 68.56865 3.1952274 #> 10 10 A 62.17225 -3.2011733 #> 11 11 A 65.53202 0.1585967 #> 12 12 B 39.56360 -26.1200650 #> 13 13 B 61.05810 -4.6255702 #> 14 14 B 70.54463 4.8609601 #> 15 15 B 73.32349 7.6398246 #> 16 16 A 56.49687 -8.8765528 #> 17 17 A 62.49324 -2.8801821 #> 18 18 B 69.22735 3.5436825 #> 19 19 A 85.93656 20.5631399 #> 20 20 B 45.28513 -20.3985425