How to Check if Data Frame is Empty in R (With Example)

In R, you can check if a data frame is empty by using the nrow() and ncol() functions to check the number of rows and columns. If both of these values are 0, then the data frame is empty. An example of this would be if you had a data frame called “df” and you wanted to check if it was empty, you could use the following code: if (nrow(df) == 0 & ncol(df) == 0) { print(“Data frame is empty”) } else { print(“Data frame is not empty”) }


The fastest way to check if a data frame is empty in R is to use the nrow() function:

nrow(df)

This function returns the number of a rows in a data frame.

If the function returns 0, then the data frame is empty.

If you’d like to check if a data frame is empty in an if else function, you can use the following syntax to do so:

#create if else statement that checks if data frame is empty
if(nrow(df) == 0){
  print("This data frame is empty")
}else{
  print("This data frame is not empty")
}

The following example shows how to check if a data frame is empty in practice.

Related:

Example: Check if Data Frame is Empty in R

Suppose we create the following data frame in R that has three columns but is completely empty:

#create empty data frame
df <- data.frame(player = character(),
                 points = numeric(),
                 assists = numeric())

#view data frame
df

[1] player  points  assists
<0 rows> (or 0-length row.names)

We can use the nrow() function to check how many rows are in the data frame:

#display number of rows in data frame
nrow(df)

[1] 0

Since the function returns 0, this tells us that the data frame is empty.

We can also use the following if else statement to tell us whether or not the data frame is empty:

#create if else statement that checks if data frame is empty
if(nrow(df) == 0){
  print("This data frame is empty")
}else{
  print("This data frame is not empty")
}

[1] "This data frame is empty"

From the output we can see that the data frame is indeed empty.

The following tutorials explain how to perform other common tasks in R:

x