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)
}
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).
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.
You can use the attribute df. empty to check whether it's empty or not: if df. empty: print('DataFrame is empty!
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
Constructing if
statements is very simple, depening on what you want to check you can do
NULL
*The object is NULL
, no rows and no columns.
if (dim(df) == NULL) {
}
This data frame has columns but no observations.
if (dim(df)[1] == 0) {
}
*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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With