I'm attempting to reproduce the following code across 36 seperate columns in a df. So instead of having to retype this code 36 times, how can I apply a function to apply this for all columns at once? The columns in the df I need to apply them to are 4:40.
df <- df %>%
mutate(percent_score_1 = (score_1 / 5) * 100,
percent_score_2 = (score_2 / 5) * 100)
The data looks like this:
score_1 score_2
2 3
3 4
5 1
In case it is not clear, I am creating a percent score variable based on questions out of 5 points.
Thanks!!
You could do:
df %>%
mutate(across(starts_with('score'), ~ ./5 * 100, .names = 'percent_{col}'))
Write your own function to calculate percentage and use mutate with across.
calculate_percentage <- function(Vector){
(Vector/5) * 100
}
df %>% mutate(across(starts_with("score"),
calculate_percentage))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With