Standardize the numeric variables in a data frame

standardize(data, mean = 0, sd = 1, include_dummy = FALSE)

Arguments

data

a data frame.

mean

mean of the transformed variables.

sd

standard deviation of the transformed variables.

include_dummy

logical. If TRUE, transform dummy coded (0,1) variables.

Value

a data frame

Details

standardize transforms all the numeric variables in a data frame to have the same mean and standard deviation. By default, this will be a mean of 0 and standard deviation of 1. Character variables and factors are left unchanged. By default, dummy coded variables are also left unchanged. Use include_dummy=TRUE to transform these variables as well.

Examples

head(mtcars)
#>                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#> Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

mtcars_st <- standardize(mtcars)
head(mtcars_st)
#>                          mpg        cyl        disp         hp       drat
#> Mazda RX4          0.1508848 -0.1049878 -0.57061982 -0.5350928  0.5675137
#> Mazda RX4 Wag      0.1508848 -0.1049878 -0.57061982 -0.5350928  0.5675137
#> Datsun 710         0.4495434 -1.2248578 -0.99018209 -0.7830405  0.4739996
#> Hornet 4 Drive     0.2172534 -0.1049878  0.22009369 -0.5350928 -0.9661175
#> Hornet Sportabout -0.2307345  1.0148821  1.04308123  0.4129422 -0.8351978
#> Valiant           -0.3302874 -0.1049878 -0.04616698 -0.6080186 -1.5646078
#>                             wt       qsec vs am       gear       carb
#> Mazda RX4         -0.610399567 -0.7771651  0  1  0.4235542  0.7352031
#> Mazda RX4 Wag     -0.349785269 -0.4637808  0  1  0.4235542  0.7352031
#> Datsun 710        -0.917004624  0.4260068  1  1  0.4235542 -1.1221521
#> Hornet 4 Drive    -0.002299538  0.8904872  1  0 -0.9318192 -1.1221521
#> Hornet Sportabout  0.227654255 -0.4637808  0  0 -0.9318192 -0.5030337
#> Valiant            0.248094592  1.3269868  1  0 -0.9318192 -1.1221521