In this notebook we will learn another methods for reverse coding of questionnaire items using the R statistical programming environment. Here you will learn reverse coding using a function from the psych package in R. This notebook is for the blog post https://www.marsja.se/reverse-scoring-using-r/ in which you will learn more about this.
As example data, with some columns to reverse, we create a dataframe:
df <- as.data.frame(replicate(6, replicate(100, sample(1:5,1))))
colnames(df) <- c('Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6')
head(df)
Q1 | Q2 | Q3 | Q4 | Q5 | Q6 |
---|---|---|---|---|---|
3 | 1 | 4 | 2 | 4 | 5 |
2 | 1 | 3 | 3 | 1 | 1 |
3 | 4 | 1 | 3 | 5 | 4 |
1 | 3 | 4 | 2 | 1 | 1 |
5 | 1 | 1 | 2 | 4 | 1 |
2 | 5 | 5 | 4 | 1 | 1 |
First, we are going to install the r-package called "psych" and then we are going to sue the reverse.code function to switch the coding of some items.
install.packages("psych")
Installing package into 'C:/Users/erima96/Documents/R/win-library/3.6' (as 'lib' is unspecified)
package 'psych' successfully unpacked and MD5 sums checked The downloaded binary packages are in C:\Users\erima96\AppData\Local\Temp\Rtmpea2YXQ\downloaded_packages
Now, we're ready to reverse the items using R:
require(psych)
#Reversing scores in columns 'Q2', 'Q3', and 'Q4'
keys <- c(1, -1, -1, -1, 1, 1)
new <- reverse.code(keys, df)
df[1:3,]
new[1:3,]
Loading required package: psych Warning message: "package 'psych' was built under R version 3.6.1"
Q1 | Q2 | Q3 | Q4 | Q5 | Q6 |
---|---|---|---|---|---|
3 | 1 | 4 | 2 | 4 | 5 |
2 | 1 | 3 | 3 | 1 | 1 |
3 | 4 | 1 | 3 | 5 | 4 |
Q1 | Q2- | Q3- | Q4- | Q5 | Q6 |
---|---|---|---|---|---|
3 | 5 | 2 | 4 | 4 | 5 |
2 | 5 | 3 | 3 | 1 | 1 |
3 | 2 | 5 | 3 | 5 | 4 |