Kelsey
Kelsey

Reputation: 199

Mutate if variable name appears in a list

I would like to use dplyr to divide a subset of variables by the IQR. I am open to ideas that use a different approach than what I've tried before, which is a combination of mutate_if and %in%. I want to reference the list bin instead of indexing the data frame by position. Thanks for any thoughts!

contin <- c("age", "ct")

data %>%
  mutate_if(%in% contin, function(x) x/IQR(x))

Upvotes: 0

Views: 673

Answers (1)

Onyambu
Onyambu

Reputation: 79318

You should use:

data %>%
  mutate(across(all_of(contin), ~.x/IQR(.x)))

Working example:

data <- head(iris)
contin <- c("Sepal.Length", "Sepal.Width")

data %>%
      mutate(across(all_of(contin), ~.x/IQR(.x)))
 Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1     15.69231    7.777778          1.4         0.2  setosa
2     15.07692    6.666667          1.4         0.2  setosa
3     14.46154    7.111111          1.3         0.2  setosa
4     14.15385    6.888889          1.5         0.2  setosa
5     15.38462    8.000000          1.4         0.2  setosa
6     16.61538    8.666667          1.7         0.4  setosa

Upvotes: 2

Related Questions