Mutating across multiple columns to create percent score in R

Viewed 302

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

4 Answers

You could do:

df %>%
   mutate(across(starts_with('score'), ~ ./5 * 100, .names = 'percent_{col}'))

You can try the code below

idx <- startsWith(names(df), "score_")
cbind(df, setNames(df[idx] * 5 / 100, paste0("percent_", names(df)[idx])))

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

Update: to get the right names we could assign arguments like Onyambu did (credits to him):

library(dplyr)

my_percent_score <- function(x) {
    x=(x/5)*100
}

df %>% 
    mutate(across(starts_with('score'), my_percent_score, .names = 'percent_{col}'))
Related