Reverse Scoring Items

Just converting @eipi10's answer using tidyverse:

# Create same fake data: Three questions answered on a 1 to 5 scale
set.seed(1)
dat <- data.frame(Q1 = sample(1:5,10, replace=TRUE), 
                  Q2 = sample(1:5,10, replace=TRUE),
                  Q3 = sample(1:5,10, replace=TRUE))

# Reverse scores in the desired columns (Q2 and Q3)

dat <- dat %>% 
  mutate(Q2Reversed = 6 - Q2,
         Q3Reversed = 6 - Q3)

Here's an example with some fake data that you can adapt to your data:

# Fake data: Three questions answered on a 1 to 5 scale
set.seed(1)
dat = data.frame(Q1=sample(1:5,10,replace=TRUE), 
                 Q2=sample(1:5,10,replace=TRUE),
                 Q3=sample(1:5,10,replace=TRUE))

dat
   Q1 Q2 Q3
1   2  2  5
2   2  1  2
3   3  4  4
4   5  2  1
5   2  4  2
6   5  3  2
7   5  4  1
8   4  5  2
9   4  2  5
10  1  4  2

# Say you want to reverse questions Q1 and Q3
cols = c("Q1", "Q3")

dat[ ,cols] = 6 - dat[ ,cols]

dat
   Q1 Q2 Q3
1   4  2  1
2   4  1  4
3   3  4  2
4   1  2  5
5   4  4  4
6   1  3  4
7   1  4  5
8   2  5  4
9   2  2  1
10  5  4  4

If you have a lot of columns, you can use tidyverse functions to select multiple columns to recode in a single operation.

library(tidyverse)

# Reverse code columns Q1 and Q3
dat %>% mutate(across(matches("^Q[13]"), ~ 6 - .))

# Reverse code all columns that start with Q followed by one or two digits
dat %>% mutate(across(matches("^Q[0-9]{1,2}"), ~ 6 - .))

# Reverse code columns Q11 through Q20
dat %>% mutate(across(Q11:Q20, ~ 6 - .))

If different columns could have different maximum values, you can (adapting @HellowWorld's suggestion) customize the reverse-coding to the maximum value of each column:

# Reverse code columns Q11 through Q20 
dat %>% mutate(across(Q11:Q20, ~ max(.) + 1 - .))

Tags:

R

Reverse

Scoring