Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an empty dataframe fail an is.null() test?

Tags:

please excuse me if my question is quite basic. I created an empty data frame by df <- data.frame() and obviously the data frame is NULL (empty). when I try to check if the data frame is empty by is.null(df), the result comes FALSE. Is there any difference between NULL and empty in R. In this case if the data frame is not NULL , then what is in the empty data frame and when it will be NULL. Thanks

like image 487
Agaz Wani Avatar asked Feb 17 '15 07:02

Agaz Wani


People also ask

How do you check a DataFrame is empty or not?

You can use the attribute df. empty to check whether it's empty or not: if df. empty: print('DataFrame is empty!

Is null a DataFrame in R?

The R function is. null indicates whether a data object is of the data type NULL (i.e. a missing value). The function returns TRUE in case of a NULL object and FALSE in case that the data object is not NULL. The code above illustrates how to use is.

How do you check if a row is empty in pandas?

shape() method returns the number of rows and number of columns as a tuple, you can use this to check if pandas DataFrame is empty. DataFrame. shape[0] return number of rows. If you have no rows then it gives you 0 and comparing it with 0 gives you True .


1 Answers

df is not NULL because it is a data frame and thus has some defined properties. For instance, it has a class. And you can get the number of rows in the data frame using nrow(df), even if the result should happen to be zero. Therefore, also the number of rows is well-defined.

As fas as I know, there is no is.empty command in base R. What you could do is, e.g., the following

is.data.frame(df) && nrow(df)==0 

This will give TRUE for an empty data frame (that is, one with no rows) and false otherwise.

The reason for checking is.data.frame first is that nrow might cause an error, if it is applied to anything else than a data frame. Thanks to &&, nrow(df) will only be evaluated if df is a data frame.

like image 76
Stibu Avatar answered Sep 22 '22 16:09

Stibu