R Is Not So Hard! A Tutorial, Part 18: Re-Coding Values


One data manipulation task that you need to do in pretty much any data analysis is recode data.  It’s almost never the case that the data are set up exactly the way you need them for your analysis.

In R, you can re-code an entire vector or array at once. To illustrate, let’s set up a vector that has missing values.

A <- c(3, 2, NA, 5, 3, 7, NA, NA, 5, 2, 6)

A

[1] 3 2 NA 5 3 7 NA NA 5 2 6

We can re-code all missing values by another number (such as zero) as follows:

A[ is.na(A) ] <- 0

A

[1] 3 2 0 5 3 7 0 0 5 2 6

Let’s re-code all values less than 5 to the value 99.

A[ A < 5 ] <- 99

A

[1] 99 99 99 5 99 7 99 99 5 99 6

However, some re-coding tasks are more complex, particularly when you wish to re-code a categorical variable or factor. In such cases, you might want to re-code an array with character elements to numeric elements.

gender <- c("MALE","FEMALE","FEMALE","UNKNOWN","MALE")

gender

[1] "MALE" "FEMALE" "FEMALE" "UNKNOWN" "MALE"

Let’s re-code males as 1 and females as 2. Very useful is the following re-coding syntax because it works in many practical situations. It involves repeated (nested) use of the ifelse() command.

ifelse(gender == "MALE", 1, ifelse(gender == "FEMALE", 2, 3))

[1] 1 2 2 3 1

If you’ve never seen this type of nested command, it can be a bit confusing. The ifelse command takes some statement that may be true or false. If it is true, we assign the value after the first comma, if it is false, we assign the value after the second comma.

In this case, we first check if gender is male, and if so assign a 1 to the observation. If the gender isn’t male, we go to the second part of the code which checks for being female, assigning a 2 if female and a 3 otherwise. Together this made the element with unknown gender get re-coded as a 3. Make a note of this syntax. It’s great for re-coding within R programs.

Another example, this time using a rectangular array.

A <- data.frame(Gender = c("F", "F", "M", "F", "B", "M", "M"), Height = c(154, 167, 178, 145, 169, 183, 176))

A

    Gender Height
1      F    154
2      F    167
3      M    178
4      F    145
5      B    169
6      M    183
7      M    176

We have deliberately introduced an error where gender is misclassified as B. This one gets re-coded to the value 99. Note that the Gender variable is located in the first column, or A[ ,1].

A[,1] <- ifelse(A[,1] == "M", 1, ifelse(A[,1] == "F", 2, 99))

A

    Gender Height
1      2     154
2      2     167
3      1     178
4      2     145
5     99     169
6      1     183
7      1     176

You can use the same approach to code as many different levels as you need to. Let’s re-code for four different levels.

My last example is drawn from the films of the Lord of the Rings and the Hobbit.

The sets where Peter Jackson produced these films are just a short walk from where I live, so the example is relevant for me.

S <- data.frame(SPECIES = c("ORC", "HOBBIT", "ELF", "TROLL", "ORC", "ORC", "ELF", "HOBBIT"), HEIGHT
= c(194, 127, 178, 195, 149, 183, 176, 134))

S

    SPECIES HEIGHT
1     ORC    194
2  HOBBIT    127
3     ELF    178
4   TROLL    195
5     ORC    149
6     ORC    183
7     ELF    176
8  HOBBIT    134

We now use nested ifelse commands to re-code Orcs as 1, Elves as 2, Hobbits as 3, and Trolls as 4.

S[,1] <- ifelse(S[,1] == "ORC", 1, ifelse(S[,1] == "ELF", 2, ifelse(S[,1] == "HOBBIT", 3, ifelse(S[,1] == "TROLL", 4, 99))))

S

     SPECIES HEIGHT
1       1    194
2       3    127
3       2    178
4       4    195
5       1    149
6       1    183
7       2    176
8       3    134

We can recode back to character just as easily.

S[,1] <- ifelse(S[,1] == 1, "ORC", ifelse(S[,1] == 2, "ELF", ifelse(S[,1] == 3, "HOBBIT", ifelse(S[,1] == 4, "TROLL", 99))))

S

   SPECIES HEIGHT
1     ORC    194
2  HOBBIT    127
3     ELF    178
4   TROLL    195
5     ORC    149
6     ORC    183
7     ELF    176
8  HOBBIT    134

The general approach is the same as before, but now you have a few additional sets of parentheses.

That wasn’t so hard! In our next blog post we will learn about how to work with multiple plots at once using the par command.

About the Author: David Lillis has taught R to many researchers and statisticians. His company, Sigma Statistics and Research Limited, provides both on-line instruction and face-to-face workshops on R, and coding services in R. David holds a doctorate in applied statistics.

See our full R Tutorial Series and other blog posts regarding R programming.

 

Getting Started with R
Kim discusses the use of R statistical software for data manipulation, calculation, and graphical display.

Reader Interactions

Comments

  1. Roger Dimples says

    Er, not to be negative, but this is a pretty sloppy way of recoding. What if I want to change 5 values? Am I meant to nest four ifelse() calls?

    To take a page from Hadley Wickham’s advanced-R (adv-r.had.co.nz), it’s much easier to create a named vector.

    For your data frame A, you can do
    gender_recode <- c('F' = 1, 'M' = 2)
    A$Gender <- gender_recode[A$Gender]
    Which would then code the 'B' value as missing. Note that you can also go from numeric to string (although you must escape the numeric names with the backtick, `)

    Using match() or merge() are alternative solutions (as is the dplyr packages recode() ).


Leave a Reply

Your email address will not be published. Required fields are marked *

Please note that, due to the large number of comments submitted, any questions on problems related to a personal study/project will not be answered. We suggest joining Statistically Speaking, where you have access to a private forum and more resources 24/7.