• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Analysis Factor

The Analysis Factor

Statistical Consulting, Resources, and Statistics Workshops for Researchers

  • Home
  • About
    • Our Programs
    • Our Team
    • Our Core Values
    • Our Privacy Policy
    • Employment
    • Guest Instructors
  • Membership
    • Statistically Speaking Membership Program
    • Login
  • Workshops
    • Online Workshops
    • Login
  • Consulting
    • Statistical Consulting Services
    • Login
  • Free Webinars
  • Contact
  • Login

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

by guest 5 Comments

by David Lillis, Ph.D.

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

The element with unknown gender was re-coded as 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.

To see more of the R is Not So Hard! tutorial series, visit our R Resource page.

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.

Bookmark and Share

Tagged With: data cleaning, R, recode

Related Posts

  • R Is Not So Hard! A Tutorial, Part 9: Sub-setting
  • R Is Not So Hard! A Tutorial, Part 8: Basic Commands
  • R is Not So Hard! A Tutorial, Part 22: Creating and Customizing Scatter Plots
  • R is Not So Hard! A Tutorial, Part 21: Pearson and Spearman Correlation

Reader Interactions

Comments

  1. Mirella says

    October 3, 2017 at 5:26 am

    Great article about r programming tutorial, thanks for sharing I guess you should have a look on http://programmer.science/category/r-programming-tutorial, hope this can help you jessica (sorry not sure of your name) anyway cheers…

    Reply
  2. JFS says

    February 1, 2017 at 7:38 pm

    FYI, Part 19 of this tutorial is currently 404 / not found.

    Reply
  3. Remmie says

    August 6, 2016 at 11:27 pm

    Good morning

    Do you mean I should use 99 instead of NA or what

    Reply
  4. Roger Dimples says

    June 29, 2016 at 9:40 am

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

    Reply
    • Mimi says

      August 21, 2017 at 11:21 am

      Loved your idea! I had 12 values to recode. Your method is very clean and easy to maintain. Thanks very much!!

      Reply

Leave a Reply Cancel 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.

Primary Sidebar

This Month’s Statistically Speaking Live Training

  • January Member Training: A Gentle Introduction To Random Slopes In Multilevel Models

Upcoming Workshops

  • Logistic Regression for Binary, Ordinal, and Multinomial Outcomes (May 2021)
  • Introduction to Generalized Linear Mixed Models (May 2021)

Read Our Book



Data Analysis with SPSS
(4th Edition)

by Stephen Sweet and
Karen Grace-Martin

Statistical Resources by Topic

  • Fundamental Statistics
  • Effect Size Statistics, Power, and Sample Size Calculations
  • Analysis of Variance and Covariance
  • Linear Regression
  • Complex Surveys & Sampling
  • Count Regression Models
  • Logistic Regression
  • Missing Data
  • Mixed and Multilevel Models
  • Principal Component Analysis and Factor Analysis
  • Structural Equation Modeling
  • Survival Analysis and Event History Analysis
  • Data Analysis Practice and Skills
  • R
  • SPSS
  • Stata

Copyright © 2008–2021 The Analysis Factor, LLC. All rights reserved.
877-272-8096   Contact Us

The Analysis Factor uses cookies to ensure that we give you the best experience of our website. If you continue we assume that you consent to receive cookies on all websites from The Analysis Factor.
Continue Privacy Policy
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.

Non-necessary

Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.