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

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

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

 

table 1 matrix create dummy data frame

 

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

 

table 2 data frame create 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:

 

The YouTube video will be added soon.

 

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

 

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.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top