Create Data Frame with n Rows & m Columns in R (Example)
In this R tutorial you’ll learn how to initialize an empty data frame with particular dimensions.
Table of contents:
Let’s dive into it.
Example: Create Empty Data Frame with Certain Dimensions
This example shows how to construct a data frame containing n rows and m variables.
For this, we can use the data.frame function in combination with the matrix function.
Within the matrix function, we have to specify the number of rows using the nrow argument and the number of columns using the ncol argument.
data <- data.frame(matrix(NA, # Create empty data frame nrow = 5, ncol = 4)) data # Print empty data frame |
data <- data.frame(matrix(NA, # Create empty data frame nrow = 5, ncol = 4)) data # Print empty data frame
Have a look at Table 1. It illustrates the RStudio console output of the previous R code.
As you can see, our data frame has five rows and two columns. All data cells have been set to NA.
Video & Further Resources
Some time ago I have released a video on my YouTube channel, which illustrates the R codes of this article. You can find the video below.
The YouTube video will be added soon.
Furthermore, I can recommend reading the other articles of my website. I have released several other articles on related topics such as loops, matrices, and extracting data:
- Loop Through Data Frame Columns & Rows in R
- Extract First N Rows of Data Frame
- Sums of Rows & Columns in Data Frame or Matrix
- Unique Rows of Data Frame Based On Selected Columns
- Repeat Rows of Data Frame N Times in R
- All R Programming Examples
This article showed how to construct a data frame having n rows and m columns in the R programming language. In case you have additional questions, let me know in the comments section below. Furthermore, please subscribe to my email newsletter to receive updates on new articles.
Subscribe to my free statistics newsletter: