Standardizing Data Frame Variables in R (Example Code)
This article illustrates how to scale a data frame in R programming.
Creating Exemplifying Data
set.seed(111222333) # Setting seed my_df <- data.frame(x = runif(500), # Creating example data frame y = runif(500), z = runif(500)) head(my_df) # Head of example data frame # x y z # 1 0.5465280 0.8041262 0.06875056 # 2 0.9357472 0.1261005 0.93677202 # 3 0.9421016 0.7632489 0.56510851 # 4 0.3691926 0.2581244 0.70402491 # 5 0.9699207 0.1104580 0.24193916 # 6 0.3050477 0.2424732 0.84682478 |
set.seed(111222333) # Setting seed my_df <- data.frame(x = runif(500), # Creating example data frame y = runif(500), z = runif(500)) head(my_df) # Head of example data frame # x y z # 1 0.5465280 0.8041262 0.06875056 # 2 0.9357472 0.1261005 0.93677202 # 3 0.9421016 0.7632489 0.56510851 # 4 0.3691926 0.2581244 0.70402491 # 5 0.9699207 0.1104580 0.24193916 # 6 0.3050477 0.2424732 0.84682478
Example: Standardize Columns of Data Frame with scale Function
The following R code creates standardized data.
my_df_scale <- scale(my_df) # Using scale function in R head(my_df_scale) # Head of standardized data columns # x y z # [1,] 0.1255981 1.0215973 -1.4502444 # [2,] 1.4478506 -1.2915632 1.6004818 # [3,] 1.4694376 0.8821397 0.2942427 # [4,] -0.4768445 -0.8411488 0.7824747 # [5,] 1.5639446 -1.3449295 -0.8415601 # [6,] -0.6947573 -0.8945447 1.2843555 |
my_df_scale <- scale(my_df) # Using scale function in R head(my_df_scale) # Head of standardized data columns # x y z # [1,] 0.1255981 1.0215973 -1.4502444 # [2,] 1.4478506 -1.2915632 1.6004818 # [3,] 1.4694376 0.8821397 0.2942427 # [4,] -0.4768445 -0.8411488 0.7824747 # [5,] 1.5639446 -1.3449295 -0.8415601 # [6,] -0.6947573 -0.8945447 1.2843555