Search code examples
rdata.tablenormalize

R Normalize Many Columns


data = data.frame(cat = runif(1000), dog = runif(1000), fox = runif(1000), bunny = runif(1000))
normalize_these = c("dog", "bunny")

I wish to obtain a new version of data called dataNEW where the variable columns listed in 'normalize_these' are normalized with mean equals to 0 and standard deviation equals to 1. Is there a data.table solution to do so?


Solution

  • Try scale like below

    cbind(data, `colnames<-`(scale(data[normalize_these]), paste0(normalize_these, "NEW")))
    

    If you would like to use data.table, below might be an option

    setDT(data)
    data[, paste0(normalize_these, "NEW") := lapply(.SD, scale), .SDcols = normalize_these]