简体   繁体   中英

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.

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) 
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM