Search code examples
rdplyrplyr

Checking if an r package is currently attached


I am having trouble with my workflow because I am sourcing multiple scripts in rmarkdown, some of which require the package dplyr and some of which use plyr.

The problem is that the rename function exists in both packages and if dplyr is currently attached the rename function in plyr won't work.

How do I include in my scripts a function that checks if dplyr is attached, and, if it is, detach it?

I know how to detach packages via detach("package:dplyr", unload = TRUE). What I don't know is how to check if a package is attached or not.


Solution

  • I agree that the best approach is to use dplyr::rename and plyr::rename to explicitly call the function you want.

    However, if you did want to check if a package is attached and then detach it, use:

    if ("plyr" %in% .packages()) {
      detach("package:plyr", unload=TRUE) 
    }