I'm looking for a tidy way to perform the following:
iris %>% mutate(
petal_width_pct = Petal.Width/Sepal.Width,
petal_length_pct = Petal.Length/Sepal.Width,
sepal_length_pct = Sepal.Length/Sepal.Width,
sepal_width_pct = Sepal.Width/Sepal.Width)
I'd like to add a percentage column for each numeric column, in a way which doesn't require the listing of each variable. I imagine I need a purrr map of some kind, but I haven't figured it out yet!
Instead of map
I think you should look at across
:
library(dplyr)
iris %>% mutate(across(where(is.numeric), ~./Sepal.Width, .names ='{col}_pct'))
In dplyr
versions < 1.0.0 you could use mutate_if
with same effect.
iris %>% mutate_if(is.numeric, list(pct = ~./Sepal.Width))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments