0

Is there a more elegant (fail-safe/robust, shorter) way of checking whether a dataset (whose name is known as a character string) exists in a package than this?

rda.name <- "Animals" # name of the data set/.rda
rda.name %in% data(package = "MASS")[["results"]][,"Item"]
Marius Hofert
  • 6,546
  • 10
  • 48
  • 102

2 Answers2

3

You can try this approach using exists:

exists(data("Animals", package = "MASS"))
# [1] TRUE
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
  • 2
    `data` also has a verbose argument that will print out more information about available packages. For example, try `data("snack", verbose=TRUE)`. – lmo Dec 01 '18 at 14:29
  • I can't replicate the second part of Sven's answer. I obtain the warning `In data(rda.name, package = "MASS") : data set ‘rda.name’ not found`. This is why I specifically asked the question with a variable as name (and not the name itself as in the first part of this answer). – Marius Hofert Dec 01 '18 at 15:36
  • I now found https://stackoverflow.com/questions/19912833/load-a-dataset-into-r-with-data-using-a-variable-instead-of-the-dataset-name. The best answer seems to be the one which works with `data`'s `list` argument but then the data set is already loaded and not just checked for existence. – Marius Hofert Dec 01 '18 at 15:41
  • Also, if the dataset does *not* exist, a warning is thrown (catching that does not seem more elegant than what I did) – Marius Hofert Dec 01 '18 at 15:50
  • @MariusHofert Thanks for pointing out. The code with the variable indeed didn't work, – Sven Hohenstein Dec 01 '18 at 16:17
0

As mentioned in the comment, I cannot replicate Sven's answer (under any recent version of R). The following works, but the usage of suppressWarnings() is rather ugly and the dataset is also loaded when calling data() this way (instead of just checking its existence). As such, I don't think this is preferable over my original version, but perhaps inspires someone to provide a fix.

exists(suppressWarnings(data(list = rda.name, package = "MASS")))
Marius Hofert
  • 6,546
  • 10
  • 48
  • 102