# Create Dummy Data Frame in R (Example)

This tutorial illustrates how to **construct a data frame with dummy variables** in R.

The tutorial consists of this:

You’re here for the answer, so let’s get straight to the programming part…

## Example: Construct Dummy Data Frame Using rbinom(), matrix() & as.data.frame() Functions

The following R syntax shows how to create a data frame containing multiple dummy variables in R.

We first need to set a random seed to make this example reproducible:

set.seed(2867754) # Set seed for reproducibility |

set.seed(2867754) # Set seed for reproducibility

Next, we can use the rbinom function to generate a random dummy vector:

dummy_vec <- rbinom(15, 1, prob = 0.3) # Create dummy vector dummy_vec # Print dummy vector # [1] 1 0 0 1 0 0 0 0 0 0 0 0 1 0 1 |

dummy_vec <- rbinom(15, 1, prob = 0.3) # Create dummy vector dummy_vec # Print dummy vector # [1] 1 0 0 1 0 0 0 0 0 0 0 0 1 0 1

In the next step, we can convert this dummy vector to a matrix:

dummy_mat <- matrix(dummy_vec, ncol = 3) # Convert vector to matrix dummy_mat # Print dummy matrix |

dummy_mat <- matrix(dummy_vec, ncol = 3) # Convert vector to matrix dummy_mat # Print dummy matrix

Table 1 shows the output of the previous R programming syntax – A matrix object containing three different dummy columns.

Finally, we can convert the matrix object to the data.frame class using the as.data.frame function:

data <- as.data.frame(dummy_mat) # Convert matrix to data frame data # Print dummy data frame |

data <- as.data.frame(dummy_mat) # Convert matrix to data frame data # Print dummy data frame

As visualized in Table 2, we have managed to construct a data frame with dummy variables with the previous R programming syntax.

## Video & Further Resources

Do you need more info on the R programming syntax of this article? Then you might want to have a look at the following video on my YouTube channel. In the video, I’m explaining the contents of this article in a live session in RStudio:

**Please accept YouTube cookies to play this video.** By accepting you will be accessing content from YouTube, a service provided by an external third party.

If you accept this notice, your choice will be saved and the page will refresh.

In addition, you may want to read the related posts on this website:

- Create a Data Frame in R
- Create Empty Data Frame in R
- Create Data Frame with n Rows & m Columns
- Create Data Frame of Unequal Lengths
- Create List of Data Frames
- The R Programming Language

To summarize: At this point you should know how to **make a data frame with dummy columns** in R. Let me know in the comments section below, in case you have any additional questions.

### Statistics Globe Newsletter