Search code examples
rdplyracross

R: Transforming variables over many columns


I want to transform multiple columns in a large data.frame at once using across.

As an example I want to make this transformation

library(tidyverse)

iris %>% mutate(Sepal.Length2 = (Sepal.Length^4-min(Sepal.Length^4)) / (max(Sepal.Length^4) - min(Sepal.Length^4)))

but for all columns starting with "Sepal".

I think, I can use this command, but I can't figure how I can add my function.

iris %>% mutate(across(starts_with("Sepal")), ... )

Sorry if it is too trivial, but I don't know what I have to enter into google to find some useful pages.


Solution

  • We can use

    library(dplyr)
    iris1 <- iris %>%
        mutate(across(starts_with("Sepal"),
               ~ (.^4-min(.^4)) / (max(.^4) - min(.^4)), .names = '{.col}2'))