Search code examples
rstandardized

How to standardize selected columns in panel data frame


How do I standardize SELECTED columns in a data frame, when the data frame is a panel? Lets say, that I only want to standardize columns X2, X4, X6, X7, and X9 by explicitly selecting them in the sample data frame below, while I account for the panel data structure.

df <- data.frame(unit=rep(1:250, 4),  
             year=rep(c(2012, 2013, 2014, 2015), each=250),
             replicate(10,sample(0:50000,1000,rep=TRUE)))

To be sure: With standardizing I mean the usual subtract the mean and divide by standard deviation procedure.


Solution

  • We can use mutate_at

    library(dplyr)
    df %>%
       group_by(unit) %>%
       mutate_at(vars(X2, X4, X6, X7, X9), funs(as.vector(scale(.))))