简体   繁体   中英

transform all columns in a data frame with dplyr?

Suppose I have a data frame that looks something like this:

set.seed(9782)
df1 <- data.frame(X1 = rnorm(100, mean=123, sd=6),
                  X2 = rnorm(100, 567, 21),
                  X3 = rnorm(100, 783, 82))

I want to rescale all the columns of df1. I can do it with the following code:

means <- apply(df1, 2, mean)
sds   <- apply(df1, 2, sd)  
df1Rescaled <- data.frame(t(t(t(t(df1) - means)) / sds))

How can I do the same with dplyr?

We can use scale

df1New <- df1 %>%
            mutate_each(funs(scale))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM