Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write if/else statements if dataframe is empty in R

Tags:

r

I am trying to do the following: If there is nothing in the dataframe, print "no_match".

If there is something, bind it to the ID of dataframe df2:

if(df == []){
print("nomatch")
}else{
cbind(df, df2$id2)
}
like image 456
KerryLee Avatar asked Feb 12 '16 15:02

KerryLee


People also ask

How do I create an empty DataFrame in R?

One simple approach to creating an empty DataFrame in the R programming language is by using data. frame() method without any params. This creates an R DataFrame without rows and columns (0 rows and 0 columns).

Is empty in R?

To check if list is empty in R programming, we have to evaluate the condition that the length of list is zero. Call length() function with this list passed as argument and if the return value is 0 using equal to operator.

How do I check if a DataFrame is empty in Python?

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


2 Answers

You could get the information about the dimensions of your data frame via dim. For example running the code:

data(mtcars)
dim(mtcars)

will show you the dimensions:

[1] 32 11

For a NULL object you would get:

mtcars <- NULL
dim(mtcars)
NULL

dim is quite flexible as in case of a data.frame with no rows:

mtcars <- mtcars[-c(1:dim(mtcars)[1]),]

you will get

> dim(mtcars)
[1]  0 11

IF statements

Constructing if statements is very simple, depening on what you want to check you can do

Object is NULL

*The object is NULL, no rows and no columns.

if (dim(df) == NULL) {
}

No rows

This data frame has columns but no observations.

if (dim(df)[1] == 0) {

}

No columns

*The object is still of class data.frame but has no data.

if (dim(df)[2] == 0) {

}

You would construct the object like that (if of interest):

data(mtcars)
mtcars <- mtcars[,-c(1:dim(mtcars)[2])]

Naturally, you can combine conditions to check for both or one event of data frame being empty.

like image 161
Konrad Avatar answered Oct 19 '22 10:10

Konrad


It depends, is your data.frame actually empty or are all the elements something you consider empty.

If the data.frame is empty you can use nrow as a simple check.

tmp <- data.frame(A = numeric())
nrow(tmp)
[1] 0

if(nrow(tmp) == 0){
    print("data.frame is empty")
}else{
    print("data.frame contains data")
}

EDIT - OP asks about object existence

You can check if an object has been defined with exists

exists("tmp2")
[1] FALSE
exists("tmp")
[1] TRUE
like image 37
cdeterman Avatar answered Oct 19 '22 11:10

cdeterman