Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutating across multiple columns to create percent score in R

Tags:

r

dplyr

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!!

like image 215
jarciniegas Avatar asked Nov 19 '25 01:11

jarciniegas


2 Answers

You could do:

df %>%
   mutate(across(starts_with('score'), ~ ./5 * 100, .names = 'percent_{col}'))
like image 66
KU99 Avatar answered Nov 20 '25 16:11

KU99


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))
like image 41
Jason Mathews Avatar answered Nov 20 '25 17:11

Jason Mathews



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!