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

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

by Erma Khan
spot_img

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: An Introduction to the nrow Function in R (With Examples)

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 frame(player = character(),
                 points = numeric(),
                 assists = numeric())

#view data frame
df

[1] player  points  assists
 (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.

Additional Resources

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

How to Create an Empty Data Frame in R
How to Add an Empty Column to a Data Frame in R
How to Remove Empty Rows from Data Frame in R

spot_img

Related Posts