How to define dimensions of an empty DataFrame in R ?
Last Updated :
21 Apr, 2021
An empty data frame in R Programming Language corresponds to the tabular structure where the axes are of length 0, i.e. it does not contain any data items. It is basically a tabular structure organized into rows and columns consisting of all empty data vectors. A data frame can be empty in the following cases :
- A data frame with empty vectors.
- Creating a data frame of NULL entries.
Method 1: Defining the dataframe with empty vectors.
An empty data frame can be created by using only 0-length variables for column names. The data types can also be declared for these columns to specify the type of data if we wish to. In this case, the dimensions of the data frame are 0 x number of columns, but the data frame is considered empty, since it doesn’t contain any entries.
Syntax:
data.frame(column1 = data_type(col1),…)
Example
R
data_frame <- data.frame (col1 = character (0), col2 = numeric (0))
print ( "Data Frame : " )
print (data_frame)
|
Output
[1] “Data Frame : “
[1] col1 col2
<0 rows> (or 0-length row.names)
In case, a single type of data type is to be assigned to all the columns of the data frame, the data type can be declared after all the columns are initialized with NA values.
Example
R
data_frame1 <- data.frame (col1= NA , col2= NA , col3= NA , col4= NA )
[ numeric (0), ]
print ( "Data Frame :" )
print (data_frame1)
|
Output
[1] “Data Frame : “
[1] col1 col2 col3 col4
<0 rows> (or 0-length row.names)
Method 2 : Matrix with NULL as values
This is just another way of interpreting empty dataframe. Here, the values it stores will be NULL, but the dimension will be like a regular dataframe with values. A matrix with the required dimensions can be created. It is filled with NA or missing values. Since, the matrices and data frames are interconvertible into each other, it can then be converted to data frame. The dimensions of the data frame are equivalent to the length of the axes declared for matrix. A matrix can be declared using matrix() function in R.
Example:
R
mat <- matrix ( NA , nrow = 5, ncol = 2)
data_frame <- data.frame (mat)
print ( "Data Frame : " )
print (data_frame)
dim (data_frame)
|
Output
[1] “Data Frame : “
X1 X2
1 NA NA
2 NA NA
3 NA NA
4 NA NA
5 NA NA
[1] 5 2
Share your thoughts in the comments
Please Login to comment...