Subtract mean values by grouping factor. Accepts either two vectors (data and groups) or
a data.frame
and a formula of the form data ~ groups
.
group_demean(...) # S3 method for numeric group_demean(x, groups, digits = getOption("digits"), named = FALSE, ...) # S3 method for formula group_demean(f, data, digits = getOption("digits"), named = FALSE, ...)
... | arguments passed to specific methods. |
---|---|
x | a numeric vector. |
groups | a vector of the same length as |
digits | an integer passed directly to |
named | If |
f | a formula. For use with the |
data | a |
A vector of the same length as the input data (either x
or the input
column from the data.frame
data
) where group means have been subtracted
from each element in the input data. Specifically, residuals are reported the ordinary
least squares regression lm(x ~ factor(groups))
.
# using a numeric vector and corresponding grouping vector x <- runif(50) g <- rep(letters[1:5], 10) group_demean(x, g)#> [1] -0.3750491 0.3502398 0.0871847 -0.3366483 -0.4934030 0.0105942 #> [7] 0.0136841 -0.2238090 0.2390252 0.2717191 0.4188014 -0.3091526 #> [13] -0.4793349 -0.1734710 -0.0984742 -0.2601294 -0.0805551 -0.4499147 #> [19] -0.1051555 0.4747454 -0.1659070 0.1942872 0.2217434 -0.2979000 #> [25] 0.4797373 0.2857223 -0.4326470 0.0166363 0.2019671 0.1877536 #> [31] -0.4245689 -0.2585307 -0.2127454 0.1426088 -0.0217779 -0.0236280 #> [37] 0.2223406 0.4350004 -0.3135180 -0.2839025 0.2243637 0.0147523 #> [43] 0.1281031 0.1664276 -0.4047782 0.3098009 0.2855815 0.4771361 #> [49] 0.4766641 -0.1116196# using a formula and data.frame group_demean(mpg ~ cyl, mtcars)#> [1] 1.2571429 1.2571429 -3.8636364 1.6571429 3.6000000 -1.6428571 #> [7] -0.8000000 -2.2636364 -3.8636364 -0.5428571 -1.9428571 1.3000000 #> [13] 2.2000000 0.1000000 -4.7000000 -4.7000000 -0.4000000 5.7363636 #> [19] 3.7363636 7.2363636 -5.1636364 0.4000000 0.1000000 -1.8000000 #> [25] 4.1000000 0.6363636 -0.6636364 3.7363636 0.7000000 -0.0428571 #> [31] -0.1000000 -5.2636364