Joel B Joel B - 1 year ago 59
R Question

How to run certain elements of your programme based on whether a dataframe or matrix exists in R

I have a programme where I would like to do something slightly different if a certain df has already been created but the below won't work. Any suggestions? Also, would it be different for a matrix?

if (exists(df)) {
# do somthing
} else {
# do other thing

Answer Source

Try this (you would need to put the variable name in "" (it needs to be a character string) for exists, e.g. "df"):

df <- data.frame(a = 3)

if (exists("df")) {
  print("df exists")
} else {
  print("df does not exist")

See documentation for exists.