rnorouzian
rnorouzian

Reputation: 7517

Standardizing and renaming variables in a data.frame in R?

I'm trying to standardize all variables in a given data.frame, and add these standardized variables to the original data.frame with some prefix name like "s." (e.g., if original variable's name was wt, the standard one is s.wt).

My function below does that but I'm wondering why I can NOT access the new standardized variables? (see example below)

standard <- function(dataframe = mtcars){

  var.names <- names(dataframe)

dataframe$s <- as.data.frame(lapply(dataframe[, var.names], scale))

 dataframe
}
# Example:
(d <- standard()) # HERE I see the new standardized variables with prefix "s."

d$s.wt # NULL     # but HERE I can't access the standard variables!!!

Upvotes: 2

Views: 596

Answers (1)

akrun
akrun

Reputation: 887691

Assuming that we need to have new columns with suffix 's', in the OP's function, the assignment is to a single column i.e. dataframe$s while the number of scaled columns returned by the list is the same as the number of columns in the dataset. So, we can use paste to create new column with suffix 's'

standard <- function(dataframe = mtcars){
  var.names <- names(dataframe)
  dataframe[paste0("s.", var.names)] <- lapply(dataframe[var.names], function(x) c(scale(x)))
  dataframe
 }

standard()$s.wt
#[1] -0.610399567 -0.349785269 -0.917004624 -0.002299538  0.227654255  0.248094592  0.360516446 -0.027849959 -0.068730634  0.227654255  0.227654255
#[12]  0.871524874  0.524039143  0.575139986  2.077504765  2.255335698  2.174596366 -1.039646647 -1.637526508 -1.412682800 -0.768812180  0.309415603
#[23]  0.222544170  0.636460997  0.641571082 -1.310481114 -1.100967659 -1.741772228 -0.048290296 -0.457097039  0.360516446 -0.446876870

NOTE: The output of scale is a matrix with a single column, By using c, it is converted to a vectorr

Also, we can apply the function on the entire dataset

mtcars[paste0("s.", names(mtcars))] <- scale(mtcars)
identical(mtcars$s.wt, standard()$s.wt)
#[1] TRUE

Upvotes: 3

Related Questions