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
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.
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.
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.
Statistics Globe Newsletter
4 Comments. Leave new
Hello,
I have csv file of large number of columns and rows and I want to do a dataframe of this file. How can I do it.
Kind regards,
Hello Mohamed,
You can use the tidyverse package for importing a CSV file. If it has not been installed yet, first install it as follows.
Then you can follow the next steps. You should first copy the file path of your csv file. Then you can save the data as shown below.
You are now ready to use your data in your analysis. It is successfully imported.
Regards,
Cansu
Hello, I have already imported the file. My file has 140 columns and 50 rows all of them have different values. I want to know how to do dataframe of the file after after importing the file.
Hello Mohamed,
You can simply use your file name (original or the assigned name). Didn’t it work so? If the problem is the format of the data, then you can use as.data.frame() function.
Regards,
Cansu