R scale() Function - Data Standardization
The R scale() function is used to standardize data (z-score standardization).
Standardized data has a mean of 0 and a standard deviation of 1, often used to eliminate the effects of different scales.
The syntax of the scale() function is as follows:
scale(x, center = TRUE, scale = TRUE)
Parameter Description:
-
x Input a numeric matrix or data frame.
-
center Whether to center (subtract the mean), TRUE by default.
-
scale Whether to scale (divide by the standard deviation), TRUE by default.
Example
Raw data: variables with different scales
height
<-
c
(
160
,
170
,
165
,
175
,
180
)
Range 160-180
income
<-
c
(
50000
,
60000
,
55000
,
80000
,
90000
)
Range 50000-90000
age
<-
c
(
25
,
30
,
28
,
35
,
40
)
Range 25-40
Combine into a matrix
data_matrix
<-
cbind
(
height, income, age
)
(
"Original data:"
)
(
data_matrix
)
Standardization
scaled_data
<-
scale
(
data_matrix
)
(
"After standardization (mean 0, std 1):"
)
(
round
(
scaled_data,
3
)
)
Verify the mean and standard deviation
(
"Column means after standardization (should be near 0):"
)
(
round
(
colMeans
(
scaled_data
)
,
3
)
)
(
"Column standard deviations after standardization (should equal 1):"
)
(
round
(
apply
(
scaled_data,
2
,
sd
)
,
3
)
)
The output of the code above is:
[1] "原始数据:"
height income age
[1,] 160 50000 25
[2,] 170 60000 30
[3,] 165 55000 28
[4,] 175 80000 35
[5,] 180 90000 40
[1] "标准化后(均值为0,标准差为1):"
height income age
[1,] -1.2649 -1.2647 -1.2649
[2,] 0.0000 -0.4739 0.0000
[3,] -0.6325 -0.8699 -0.6325
[4,] 0.6325 0.7109 0.6325
[5,] 1.2649 1.8976 1.2649
[1] "标准化后各列均值(应接近0):"
height income age
0 0 0
[1] "标准化后各列标准差(应等于1):"
height income age
1 1 1
R Language Examples