Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an r package is currently attached

Tags:

r

dplyr

plyr

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.

like image 994
llewmills Avatar asked Jun 06 '16 23:06

llewmills


People also ask

How do you check if I have installed a package in R?

packages() Calling installed. packages() returns a detailed data frame about installed packages, not only containing names, but also licences, versions, dependencies and more.

Where is R package installed?

R packages are installed in a directory called library. The R function . libPaths() can be used to get the path to the library.

How do I clear loaded packages in R?

You can do both by restarting your R session in RStudio with the keyboard shortcut Ctrl+Shift+F10 which will totally clear your global environment of both objects and loaded packages.


2 Answers

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

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

if("plyr" %in% (.packages())){
  detach("package:plyr", unload=TRUE) 
}
like image 108
SymbolixAU Avatar answered Oct 09 '22 21:10

SymbolixAU


Worth noting here is that the packages themselves warn you to load them in a specific order. If you load dplyr, then plyr, you'll get a warning:

You have loaded plyr after dplyr - this is likely to cause problems. If you need functions from both plyr and dplyr, please load plyr first, then dplyr: library(plyr); library(dplyr)

My understanding is that dplyr doesn't work well if its functions get deprecated by plyr, but since the functions that dplyr deprecates from plyr are effectively updates, they should play nicely. So just make sure you load them in the right order:

library(plyr)
library(dplyr)

EDIT: I re-read your question, and your problem is a deprecation of plyr function by dplyr, so my point isn't very relevant to you, sorry. I'll leave it here in case someone else needs the information, since it caused me issues a while back :P

like image 33
rosscova Avatar answered Oct 09 '22 20:10

rosscova