Tomas Greif
Tomas Greif

Reputation: 22661

Check if data frame exists

What is the preferred way to check that data frame exists given you have data frame name as string? I can think of:

df_name <- 'iris'

# Option 1
tryCatch(is.data.frame(get(df_name)), error=function(cond) FALSE)

# Option 2
if (exists(df_name)) is.data.frame(get(df_name)) else FALSE

Upvotes: 22

Views: 39313

Answers (4)

ojalaquellueva
ojalaquellueva

Reputation: 73

A warning to anyone who (like me) stumbles on the accepted answer years later and carelessly misinterprets df_name as the name of a data frame...it is not. It is a string, as clearly stated by the OP.

If using an actual data frame name, you must place the data frame name in quotes in both cases:

df <- setNames(data.frame(matrix(c(1,2,3,4),nrow=2,ncol=2)), c("a","b"))

exists(df) && is.data.frame(get(df))
Error in exists(df) : invalid first argument

exists("df") && is.data.frame(get(df))
Error in get(df) : invalid first argument

exists("df") && is.data.frame(get("df"))
[1] TRUE

Upvotes: 4

user2653586
user2653586

Reputation: 219

exists("df_name") would give a TRUE (if the data frame exist) and FALSE (if it doesn't). So why bother? The trycatch statement in the first response did not work. It's output was FALSE all the time.

Upvotes: 1

Sven Hohenstein
Sven Hohenstein

Reputation: 81733

The second option can be shortened to

exists(df_name) && is.data.frame(get(df_name))

The operator && allows lazy evaluation, i.e., the second statement is only evaluated if the first one returns TRUE.

Upvotes: 32

Wilmer E. Henao
Wilmer E. Henao

Reputation: 4302

Another one

ifelse(any(ls() %in% "a"), is.data.frame(get("a")),FALSE)

Upvotes: 0

Related Questions