Getting a list of functions and objects in a package

Problem

You want to find out what’s in a package.

Solution

This code snippet will list the functions and objects in a package.

  1. # Using search() in a new R session says that these packages are
  2. # loaded by default:
  3. # "package:stats" "package:graphics"
  4. # "package:grDevices" "package:utils" "package:datasets"
  5. # "package:methods" "package:base"
  6. # Others that are useful:
  7. # gplots
  8. # ggplot2, reshape, plyr
  9. showPackageContents <- function (packageName) {
  10. # Get a list of things contained in a particular package
  11. funlist <- objects(packageName)
  12. # Remove things that don't start with a letter
  13. idx <- grep('^[a-zA-Z][a-zA-Z0-9._]*', funlist)
  14. funlist <- funlist[idx]
  15. # Remove things that contain arrow <-
  16. idx <- grep('<-', funlist)
  17. if (length(idx)!=0)
  18. funlist <- funlist[-idx]
  19. # Make a data frame to keep track of status
  20. objectlist <- data.frame(name=funlist,
  21. primitive=FALSE,
  22. func=FALSE,
  23. object=FALSE,
  24. constant=FALSE,
  25. stringsAsFactors=F)
  26. for (i in 1:nrow(objectlist)) {
  27. fname <- objectlist$name[i]
  28. if (exists(fname)) {
  29. obj <- get(fname)
  30. if (is.primitive(obj)) {
  31. objectlist$primitive[i] <- TRUE
  32. }
  33. if (is.function(obj)) {
  34. objectlist$func[i] <- TRUE
  35. }
  36. if (is.object(obj)) {
  37. objectlist$object[i] <- TRUE
  38. }
  39. # I think these are generally constants
  40. if (is.vector(obj)) {
  41. objectlist$constant[i] <- TRUE
  42. }
  43. }
  44. }
  45. cat(packageName)
  46. cat("\n================================================\n")
  47. cat("Primitive functions: \n")
  48. cat(objectlist$name[objectlist$primitive])
  49. cat("\n")
  50. cat("\n================================================\n")
  51. cat("Non-primitive functions: \n")
  52. cat(objectlist$name[objectlist$func & !objectlist$primitive])
  53. cat("\n")
  54. cat("\n================================================\n")
  55. cat("Constants: \n")
  56. cat(objectlist$name[objectlist$constant])
  57. cat("\n")
  58. cat("\n================================================\n")
  59. cat("Objects: \n")
  60. cat(objectlist$name[objectlist$object])
  61. cat("\n")
  62. }
  63. # Run the function using base package
  64. showPackageContents("package:base")