[This article was first published on Mollie's Research Blog
, and kindly contributed to R-bloggers
]. (You can report issue about the content on this page here
Want to share your content on R-bloggers? click here
if you have a blog, or here
if you don't.
If you use attach, it is easy to tell if a variable exists. You can simply use exists to check:
However, if you don’t use attach (and I find you generally don’t want to), this simple solution doesn’t work.
Instead of using exists, you can use in or any from the base package to determine if a variable is defined in a data frame:
> "varName" %in% names(df)
> any(names(df) == "varName")
Or to determine if a variable is defined in a matrix:
> "varName" %in% colnames(df)
> any(colnames(df) == "varName")