O'Reilly logo

R Data Analysis Cookbook - Second Edition by Kuntal Ganguly

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Standardizing several variables simultaneously

If you have a data frame with some numeric and some non-numeric variables, or want to standardize only some of the variables in a fully numeric data frame, then you can either handle each variable separately, which would be cumbersome, or use a function such as the following to handle a subset of variables:

scale.many <- function(dat, column.nos) {   nms <- names(dat)   for(col in column.nos) {     name <- paste(nms[col],".z", sep = "")     dat[name] <- scale(dat[,col])   }   cat(paste("Scaled ", length(column.nos), " variable(s)n"))   dat } 

With this function, you can now do things like:

> housing <- read.csv("BostonHousing.csv") > housing <- scale.many(housing, c(1,3,5:7)) 

This will add the z values ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required