Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R : Check if R object exists before creating it

Tags:

r

I am trying to skip steps loading data from large files if this has already been done earlier. Since the data ends up in (for example) mydf, I thought I could do:

if( !exists(mydf) )
{
  #... steps to do loading here.
}

I got this from How to check if object (variable) is defined in R? and https://stat.ethz.ch/R-manual/R-devel/library/base/html/exists.html

However R Studio simply complains with

'Error in exists(mydf) : object 'mydf' not found

Why does it complain instead of just returning 'true' or 'false'? Any tips appreciated.

like image 994
rstruck Avatar asked Jan 29 '15 15:01

rstruck


People also ask

How do I check if a vector exists in R?

Example 1: Apply exists() Function to Vector The exists function returns TRUE to the RStudio console. In other words: Yes, the vector x exists. The exists command returns FALSE, i.e. the vector y does not exist. That's it!

How do you check if an object is a vector or Dataframe in R?

To check if given object is a vector in R, call is. vector() function and pass the given object as argument to it. If the given object x is of type vector, then is. vector(x) returns TRUE , else it returns FALSE .

How do you check if a column exists in R?

If we have very large data set then it is highly that we forget the column names, therefore, we might want to check whether a particular column exists in the data frame or not if we know the column name. For this purpose, we can use grep function that will result the column name if exists in the data frame otherwise 0.

How do I check if a variable 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.


1 Answers

You should use exists("mydf") instead exists(mydf)

like image 124
Fedorenko Kristina Avatar answered Oct 12 '22 02:10

Fedorenko Kristina