0

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     
} 
Joel B
  • 103
  • 1
  • 8

3 Answers3

3

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.

Helix123
  • 3,502
  • 2
  • 16
  • 36
0

You can use is.data.frame to check if there is already a dataframe

if (is.data.frame(df)) {
# do somthing    
} else {
# do other thing     
} 

You can use is.matrix with similar use.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0
if (is.data.frame(df)) { 
# do stuff to df
} else {
# do other thing     
} 

if (is.matrix(mx)) { 
# do stuff to mx
} else {
# do other thing     
}
Joel B
  • 103
  • 1
  • 8
  • You should add some explication to your code to make a complete answer. Even correct, code only answers are not very legible. Here is how to write a good answer: https://stackoverflow.com/help/how-to-answer – Elzo Valugi Aug 16 '16 at 09:42