I have a dataset in which I work with mean-centered and standardized versions of many of the variables. In my r code I have a large list of the scale() functions that I run for all of the variables but I am wondering if there is a way to write a simple function that will optimize this process.
For example: instead of having a huge list like this...
df$Z.ROW1 <- scale(df$ROW1, scale=T)
df$Z.ROW2 <- scale(df$ROW2, scale=T)
df$Z.ROW3 <- scale(df$ROW3, scale=T)
.....
Is there a way to write a function that will create new vectors and append them to the end of the data frame based on the variables I specify to be standardized?
I found this example online:
set.seed(212)
df = matrix(rnorm(15), 5, 5))
colnames(df) <- c("ROW1", "ROW2", "ROW3", "ROW4", "ROW5")
df
ROW1 ROW2 ROW3 ROW4 ROW5
[1,] -0.2391731 0.1544909 0.1503488 -0.2391731 0.1544909
[2,] 0.6769356 1.0368712 0.5096765 0.6769356 1.0368712
[3,] -2.4403360 -0.7796077 -0.7733148 -2.4403360 -0.7796077
[4,] 1.2408845 0.6212641 1.8756660 1.2408845 0.6212641
[5,] -0.3265144 0.2994313 0.7883057 -0.3265144 0.2994313
center.scale <- function(z) {
scale(z, scale = T)
}
center.scale(df[,c("ROW1", "ROW2")])
ROW1 ROW2
[1,] -0.01534097 -0.1657064
[2,] 0.63734894 1.1398052
[3,] -1.58357932 -1.5477370
[4,] 1.03913941 0.5249004
[5,] -0.07756806 0.0487378
Which gets close but it doesn't solve the issue of creating new vectors and appending them to the end of my existing dataset. Ideally, I would like it so that the only thing I need to change is the variable names in the center.scale() function. Thanks!