Create Data Frame of Unequal Lengths in R (Example)
In this article you’ll learn how to create a data frame with columns that have an unequal length in the R programming language.
Table of contents:
Here’s the step-by-step process:
Creation of Example Data
First, I’ll have to create some example data:
x1 <- 1:8 # Create first example variable x1 # Print first example variable #  1 2 3 4 5 6 7 8
The previous output of the RStudio console shows the structure of our first vector (i.e. data frame variable). This first vector contains eight vector elements.
Let’s create another variable:
x2 <- letters[1:5] # Create second example variable x2 # Print second example variable #  "a" "b" "c" "d" "e"
Our second vector consists of only five elements, i.e. the length is different compared to the first vector.
First, we can apply the length and max functions to return the maximum length of our vector objects:
max_length <- max(c(length(x1), length(x2))) # Find out maximum length max_length # Print maximum length #  8
After running the previous R code, the RStudio console returns the maximum length of our variables (i.e. 8).
Now, we can use this information to create a data frame with NA values at the bottom of each column that is shorter as the maximum length.
Consider the following R syntax:
data <- data.frame(col1 = c(x1, # Create data frame with unequal vectors rep(NA, max_length - length(x1))), col2 = c(x2, rep(NA, max_length - length(x2)))) data # Print final data frame
After executing the previous code, we have created Table 1, i.e. a data frame containing the values of our two example vectors. As you can see, the second column has NA values at the bottom.
Video & Further Resources
Have a look at the following video of my YouTube channel. In the video, I illustrate the topics of this article in a live session:
Furthermore, you may want to read some of the related articles on this homepage:
- Create Data Frame with n Rows & m Columns
- Create Data Frame where a Column is a List
- Create List of Data Frames in R
- Merge Two Unequal Data Frames & Replace NA with 0
- R Programming Examples
Summary: In this article, I have illustrated how to construct a data frame where the variables have a different or uneven length in the R programming language. Please let me know in the comments section, in case you have additional comments and/or questions.