center_by {quest} | R Documentation |
Centering and/or Standardizing a Numeric Vector by Group
Description
center_by
centers and/or standardized a numeric vector by group. This
is sometimes called group-mean centering and/or group-SD standardizing.
Usage
center_by(x, grp, center = TRUE, scale = FALSE)
Arguments
x |
numeric vector. |
grp |
list of atomic vector(s) and/or factor(s) (e.g., data.frame)
containing the groups. They should each have same length as |
center |
logical vector with length 1 specifying whether group-mean centering should be done. |
scale |
logical vector with length 1 specifying whether group-SD scaling should be done. |
Details
center_by
first coerces x
to a matrix in preparation for the
core of the function, which is essentially: lapply(X = split(x = x, f =
grp), FUN = scale.default)
. If the coercion results in a non-numeric matrix
(e.g., x
is a character vector or factor), then an error is returned.
An error is also returned if x
and the elements of grp
do not
have the same length.
Value
numeric vector of x
centered and/or standardized by group with
the same names as x
.
See Also
centers_by
center
centers
scale.default
Examples
chick_data <- as.data.frame(ChickWeight) # because the "groupedData" class calls
# `[.groupedData`, which is different than `[.data.frame`
center_by(x = ChickWeight[["weight"]], grp = ChickWeight[["Chick"]])
center_by(x = setNames(obj = ChickWeight[["weight"]], nm = row.names(ChickWeight)),
grp = ChickWeight[["Chick"]]) # with names
tmp_nm <- c("Type","Treatment") # b/c Roxygen2 doesn't like a c() within a []
center_by(x = as.data.frame(CO2)[["uptake"]], grp = as.data.frame(CO2)[tmp_nm],
scale = TRUE) # multiple grouping vectors