COMET
  • Get Started
    • Quickstart Guide
    • Install and Use COMET
    • Get Started
  • Learn By Skill Level
    • Getting Started
    • Beginner
    • Intermediate - Econometrics
    • Intermediate - Geospatial
    • Advanced

    • Browse All
  • Learn By Class
    • Making Sense of Economic Data (ECON 226/227)
    • Econometrics I (ECON 325)
    • Econometrics II (ECON 326)
    • Statistics in Geography (GEOG 374)
  • Learn to Research
    • Learn How to Do a Project
  • Teach With COMET
    • Learn how to teach with Jupyter and COMET
    • Using COMET in the Classroom
    • See COMET presentations
  • Contribute
    • Install for Development
    • Write Self Tests
  • Launch COMET
    • Launch on JupyterOpen (with Data)
    • Launch on JupyterOpen (lite)
    • Launch on Syzygy
    • Launch on Colab
    • Launch Locally

    • Project Datasets
    • Github Repository
  • |
  • About
    • COMET Team
    • Copyright Information
  1. R Notebooks
  2. Creating Variables (5)
  • Learn to Research


  • STATA Notebooks
    • Setting Up (1)
    • Working with Do-files (2)
    • STATA Essentials (3)
    • Locals and Globals (4)
    • Opening Datasets (5)
    • Creating Variables (6)
    • Within Group Analysis (7)
    • Combining Datasets (8)
    • Creating Meaningful Visuals (9)
    • Combining Graphs (10)
    • Conducting Regression Analysis (11)
    • Exporting Regression Output (12)
    • Dummy Variables and Interactions (13)
    • Good Regression Practices (14)
    • Panel Data Regression (15)
    • Difference in Differences (16)
    • Instrumental Variable Analysis (17)
    • STATA Workflow Guide (18)

  • R Notebooks
    • Setting Up (1)
    • Working with R Scripts (2)
    • R Essentials (3)
    • Opening Datasets (4)
    • Creating Variables (5)
    • Within Group Analysis (6)
    • Combining Datasets (7)
    • Creating Meaningful Visuals (8)
    • Combining Graphs (9)
    • Conducting Regression Analysis (10)
    • Exporting Regression Output (11)
    • Dummy Variables and Interactions (12)
    • Good Regression Practices (13)
    • Panel Data Regression (14)
    • Difference in Differences (15)
    • Instrumental Variable Analysis (16)
    • R Workflow Guide (17)

  • Pystata Notebooks
    • Setting Up (1)
    • Working with Do-files (2)
    • STATA Essentials (3)
    • Locals and Globals (4)
    • Opening Datasets (5)
    • Creating Variables (6)
    • Within Group Analysis (7)
    • Combining Datasets (8)
    • Creating Meaningful Visuals (9)
    • Combining Graphs (10)
    • Conducting Regression Analysis (11)
    • Exporting Regression Output (12)
    • Dummy Variables and Interactions (13)
    • Good Regression Practices (14)
    • Panel Data Regression (15)
    • Difference in Differences (16)
    • Instrumental Variable Analysis (17)
    • STATA Workflow Guide (18)

On this page

  • Prerequisites
  • Learning Outcomes
  • 5.1 Review of the Data Loading Procedure
  • 5.2 Generating Dummy Variables
    • 5.2.1 Creating dummy variables using ifelse
    • 5.2.2 Creating a series of dummy variables using ifelse
    • 5.2.3 Creating Dummy Variables using case_when
  • 5.3 Generating Variables Based on Expressions
  • 5.4 Following Good Naming Conventions
  • 5.5 Wrap Up
  • 5.6 Wrap-up Table
  • Report an issue

Other Formats

  • Jupyter
  1. R Notebooks
  2. Creating Variables (5)

05 - Generating Variables

econ 490
r
generating variables
dummy variables
ifelse
case when
mutating
naming
In this notebook, we go over how to create variables. We look into how creating dummy variables works, as well as how to create variables using mathematical expressions.
Author

Marina Adshade, Paul Corcuera, Giulia Lo Forte, Jane Platt

Published

29 May 2024

Prerequisites

  1. Import data sets in .csv and .dta format.
  2. Save files.

Learning Outcomes

  1. Generate dummy (or indicator) variables using ifelse and case_when.
  2. Create new variables using mutate.
  3. Rename variables using rename.

5.1 Review of the Data Loading Procedure

We’ll continue working with the fake data set introduced in the previous lecture. Recall that this data set is simulating information of workers in the years 1982-2012 in a fake country where a training program was introduced in 2003 to boost their earnings.

In the previous module (Module 4), we looked at the process of loading our “fake_data” data set into R and preparing it for analysis. Specifically, we covered the following important points:

  1. Importing the relevant package (haven) which gives us access to commands for loading the data. Additionally, importing the tidyverse package in order to clean our data.
  2. Using the read_csv or read_dta functions to load our data set.
  3. Cleaning our data by factorizing all important variables.

Let’s run through this procedure quickly so that we are all ready to do our analysis.

library(haven)
library(tidyverse)
library(IRdisplay)
fake_data <- read_dta("../econ490-stata/fake_data.dta")
fake_data <- as_factor(fake_data)

5.2 Generating Dummy Variables

Dummy variables are variables that can only take on two values: 0 and 1. It is useful to think of a dummy variable as the answer to a “yes” or “no” question. With a dummy variable, the answer yes is coded as “1” and no is coded as “0”.

Examples of question that are used to create dummy variables include:

  1. Is the person female? Females are coded “1” and everyone else is coded “0”.
  2. Does the person have a university degree? People with a degree are coded “1” and everyone else is coded “0”.
  3. Is the person married? Married people are coded “1” and everyone else is coded “0”.
  4. Is the person a millennial? People born between 1980 and 1996 are coded “1” and those born in other years are coded “0”.

As you have probably already figured out, dummy variables are used primarily for data that is qualitative and cannot be ranked in any way. For example, being married is qualitative and “married” is neither higher nor lower than “single”. But they are sometimes also used for variables that are qualitative and ranked, such as level of education. Further, dummy variables are sometimes used for variables that are quantitative, such as age groupings.

It is important to remember that dummy variables must always be used when we want to include categorical (qualitative) variables in our analysis. These are variables such as sex, gender, race, marital status, religiosity, immigration status etc. We can’t use these variables without creating a dummy variable because the results found would in no way be meaningful, as we are working with variables which have been numerically scaled in an arbitrary way. This is especially true for interpreting the coefficients outputted from regression.

5.2.1 Creating dummy variables using ifelse

We can use the ifelse function to create a simple dummy variable. This command generates a completely new variable based on certain conditions. Let’s do an example where we create a dummy variable that indicates if the observation identified as female.

fake_data$female = ifelse(fake_data$sex == "F", 1, 0)

What R interprets here is that IF the condition sex == "F" holds, our dummy will take the value of 1; otherwise (ELSE), it will take the value of 0. Depending on what we’re doing, we may want it to be the case that when sex is missing, our dummy is zero. We can first check if we have any missing observations for a given variable by using the is.na function nested within the any function. If there are any missing values for the sex variable in this data set, the code below will return TRUE. This helps us see whether any data is in fact missing for sex.

any(is.na(fake_data$sex))

It appears that there are no missing observations for the sex variable. Nonetheless, if we wanted to account for missing values and ensure that they were denoted as 0 for the dummy female, we can invoke the is.na function as an additional condition in our function as is done below.

fake_data$female = ifelse(fake_data$sex == "F" & !is.na(fake_data$sex), 1, 0)

The above condition within our function says that female == 1 only when sex == “F” and sex is not marked as NA (since !is.na must be TRUE).

5.2.2 Creating a series of dummy variables using ifelse

We now know how to create singular dummy variables with ifelse. However, we may also want to create dummy variables corresponding to a whole set of categories for a given variable - for example, one for each region identified in the data set. To do this, we can just meticulously craft a dummy for each category, such as reg1, reg2, reg3, and reg4. We must leave out one region to serve as our base group, being region 5, in order to avoid the dummy variable trap. The reason why we do this will be explained in greater detail in a future notebook; for now, just take it as given.

fake_data$reg1 = ifelse(fake_data$region == 1 & !is.na(fake_data$region), 1, 0)
fake_data$reg2 = ifelse(fake_data$region == 2 & !is.na(fake_data$region), 1, 0)
fake_data$reg3 = ifelse(fake_data$region == 3 & !is.na(fake_data$region), 1, 0)
fake_data$reg4 = ifelse(fake_data$region == 4 & !is.na(fake_data$region), 1, 0)

This command helped us generate four new dummy variables, one for each category for each region. This was quite cumbersome though. In general, there are packages out there which help to expedite this process in R. Fortunately, if we are running a regression on a qualitative variable such as region, R will generate the necessary dummy variables for us automatically!

5.2.3 Creating Dummy Variables using case_when

We can also use more complex functions to create dummy variables. An important one is the case_when function. This function creates different values for an input based on specified cases. Specifically, it consists of a series of lines, and each line gives a (i) case and (ii) value for that case. This function is nearly always used to operate on either strings or variables which do not have numerical significance in terms of how they are coded. Otherwise, we could use simple operators such as <, >, and = to classify values of these variables and then invoke the ifelse function as we did above. Unfortunately, we don’t have any variables in our “fake_data” data set which call for this and so we don’t have an example fit for this function. However, to see documentation for this useful case_when function, run the code cell below!

?case_when

5.3 Generating Variables Based on Expressions

Sometimes we want to generate variables after some transformations (e.g. squaring, taking logs, combining different variables). We can do that by simply writing the expression as an argument to the function mutate. This function manipulates our data frame by supplying to it a new column based on the function we input. For example, let’s create a variable called log_earnings which is the log of earnings.

fake_data <- fake_data %>% mutate(log_earnings = log(earnings))

summary(fake_data$log_earnings)

Let’s try a second example. Let’s create a new variable that is the number of years since the year the individual started working.

fake_data <- fake_data %>% mutate(experience_proxy = year - start_year)

summary(fake_data$experience_proxy)

Try this out for yourself! Can you create a variable that indicates the number of years until/since the training program?

#try here!

The mutate function allows us to easily add new variables to our data frame. If we wanted to instead replace a given variable with a new feature, say add one default year to all experience_proxy observations, we can simply redefine it directly in our data frame.

fake_data$experience_proxy <- fake_data$experience_proxy + 1

5.4 Following Good Naming Conventions

Choosing good names for our variables is more important, and harder, than we might think! Some of the variables in an original data set may have very unrecognizable names, which can be confusing when conducting research. In these cases, changing them early on is preferable. We will also be creating our own variables, such as dummy variables for qualitative measures, and we will want to be careful about giving them good names. This will become even more pertinent once we start generating tables, since we will want all of our variables to have high-quality names that will easily carry over to a paper for ease of comprehension on the reader’s part.

We can rename variables with the rename function found inside the dplyr package (which we can access via having loaded in R’s tidyverse). Let’s try to rename one of those dummy variables we created above. Maybe we know that if region = 3 then the region is in the west.

rename(fake_data, west = reg3)

Don’t worry about including every piece of information in your variable names. Instead, just try to be clear and concise. Avoid variable names that include unnecessary pieces of information and can only be interpreted by you. At the end of the day, you want others to be able to understand your work.

5.5 Wrap Up

When we are doing our own research, we always have to spend some time working with the data before beginning analysis. In this module, we have learned some important tools for manipulating data to get it ready for that analysis. Like everything else that we do in R, these manipulations should be done in a script, so that we always know exactly what we have done with our data. Losing track of those changes can cause some very serious mistakes when we start to do our research! In the next module, we will look at how to do analysis on the sub-groups of variables in our data set.

5.6 Wrap-up Table

Command Function
ifelse() It creates a variable taking two values, based on whether it satisfies one certain condition.
case_when() It creates a variable taking multiple values, based on whether it satisfies multiple conditions.
mutate It creates a new variable based on an expression.
rename It renames a variable.
Opening Datasets (4)
Within Group Analysis (6)
  • Creative Commons License. See details.
 
  • Report an issue
  • The COMET Project and the UBC Vancouver School of Economics are located on the traditional, ancestral and unceded territory of the xʷməθkʷəy̓əm (Musqueam) and Sḵwx̱wú7mesh (Squamish) peoples.