R: Transforming variables over many columns

Viewed 45

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.

2 Answers

We can use

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

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

Output:

   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
1       676.5198   150.05983          1.4         0.2     setosa
2       576.4798    80.99733          1.4         0.2     setosa
3       487.9678   104.85493          1.3         0.2     setosa
4       447.7453    92.34943          1.5         0.2     setosa
5       624.9997   167.95893          1.4         0.2     setosa
6       850.3053   231.34143          1.7         0.4     setosa
7       447.7453   133.63093          1.4         0.3     setosa
8       624.9997   133.63093          1.5         0.2     setosa
9       374.8093    70.72543          1.4         0.2     setosa
10      576.4798    92.34943          1.5         0.1     setosa
11      850.3053   187.41343          1.5         0.2     setosa
12      530.8413   133.63093          1.6         0.2     setosa
13      530.8413    80.99733          1.4         0.1     setosa
14      341.8798    80.99733          1.1         0.1     setosa
15     1131.6493   255.99733          1.2         0.2     setosa
.....
Related