Skip to Main Content

Learn R

This guide focuses on transformation and cleaning functions in R that are especially useful for working with tabular datasets.

Recoding Variables in R

Recoding allows you to create new variables and to replace existing values of a variables based on a criterion.

Replace the data for an existing variable

This way we can replace the data for every row without any criteria.  

nhs_subset_1 is the new subsetted data frame which contains 100 rows and where the variable agegrp = 5 for all specified rows.

Replace data based on some criteria


In this case, we change the GROSRT to 5 only when it is 1000.

Replace data based on values in more than one variable

In the case above, we use multiple conditions to change the value for one variable, we set the GROSRT to 500 for males (SEX =2) with GROSRT equal to 1000.

Recode function

We can also use the recode function to change the values of a group or range of variables.

To use the recode function, make sure you have the "car" package installed and loaded.

> install.packages(car)
> library(car)


Liaison Librarian

Profile Photo
Martin Morris
Schulich Library of Physical Sciences, Life Sciences and Engineering
Macdonald-Stewart Library Building
809 rue Sherbrooke Ouest
Montréal, Québec H3A 0C1
(514) 398 8140
Website Skype Contact: martinatmcgill
Social: Twitter Page

McGill LibraryQuestions? Ask us!
Privacy notice