4.8.15

Recoding multiple variables in a data frame

I had a dataset with a number of variables on knowledge. The response options for the variables were coded as 1, 2 and 3. I wanted to recode them to 1 or 0 depending on whether the answers were right or wrong. However, it would be inefficient to recode every single variable in R, although it could be just a matter of copy/paste/edit task. I was thinking of looping through the relevant columns, assigning new values in each iteration, but looping would make the code difficult to digest and ugly to look at. I simply could not stand ugly codes

I had gone through a number of blogs and websites to find the most elegant way to solve this problem, but to no avail. The best solution I could find was at http://rprogramming.net/recode-data-in-r/, but I didn't like apply+function as it would be an overkill for medical personnel and researchers (of whom I deal with on daily basis) without programming basics. I need an extremely simple solution so that people won't shy away from R. I could not get the problem off my mind until I finally found a simple solution on my own :-) Here I share the codes:
library("car")

# create a data frame
data = read.table(header=T, text="
Q1  Q2  Q3  Q4  Q5
2   2   2   2   1
2   1   2   1   2
2   2   2   2   2
3   3   3   1   1
2   2   2   2   1
                  ")

# Let say for Q1, Q3 and Q5, the correct option is 3, thus recoded as 1, the rest as 0

data.recode = data
mat = as.matrix(data.recode[c(1,3,5)])
mat = recode(mat, "3=1; else=0")
data.recode[c(1,3,5)] = as.data.frame(mat)

# Let say for Q2 and Q4, the correct option is 2, thus recoded as 1, the rest as 0

mat = as.matrix(data.recode[c(2,4)])
mat = recode(mat, "2=1; else=0")
data.recode[c(2,4)] = as.data.frame(mat)

# Compare the original data with recoded ones

data
data.recode
Outputs:
> data
  Q1 Q2 Q3 Q4 Q5
1  2  2  2  2  1
2  2  1  2  1  2
3  2  2  2  2  2
4  3  3  3  1  1
5  2  2  2  2  1
> data.recode
  Q1 Q2 Q3 Q4 Q5
1  0  1  0  1  0
2  0  0  0  0  0
3  0  1  0  1  0
4  1  0  1  0  0
5  0  1  0  1  0

No comments:

Post a Comment