How can I scale(x) only certain columns of a dataframe? I have a dataframe with 7 columns and I want to scale only column 3 and 6. The rest should stay as it is.
            Asked
            
        
        
            Active
            
        
            Viewed 2.3k times
        
    9
            
            
        - 
                    1Possible duplicate of [scale() R function equivalent in Octave/Matlab](https://stackoverflow.com/questions/37378168/scale-r-function-equivalent-in-octave-matlab) – Ale Apr 19 '18 at 15:22
- 
                    Duplicate of: [R Apply() function on specific dataframe columns](https://stackoverflow.com/questions/18503177/r-apply-function-on-specific-dataframe-columns) – Ian Campbell Apr 12 '22 at 00:21
1 Answers
23
            We can do this with lapply.  Subset the columns of interest, loop through them with lapply, assign the output back to the subset of data.  Here, we are using c because the outpuf of scale is a matrix with a single column. Using c or as.vector, it gets converted to vector
df[c(3,6)] <- lapply(df[c(3, 6), function(x) c(scale(x)))
Or another option is mutate_at from dplyr
library(dplyr)
df %>%
   mutate_at(c(3,6), funs(c(scale(.))))
 
    
    
        akrun
        
- 874,273
- 37
- 540
- 662
- 
                    1
- 
                    6Late answer, but you could also simply use `df[c(3, 6)] <- scale(df[c(3, 6)])` – Nick Aug 28 '19 at 12:35
- 
                    
