I am creating an R package where I want to store several functions I wrote in the past. As I understand that I should use the double colon operator package::function whenever I call an external function, I am going through my code in RStudio to fix all function calls.
Is there a way to script/automatize this? It looks like something that should not be done manually, yet I couldn't find anywhere a way to do this.
PS: I am aware that I can also add @importFrom package function to the NAMESPACE both directly and through #' @importFrom package function, but that involves a lot of manual typing as well, plus a good deal of back and forth from the body of the function to the header.
Basically, what you want is to find patterns and prefix them with something, where
gsubis your friend.Consider the following as a sketch of an approach!
You might have a named list with names and functions of the external packages like this.
Then best cd in your working directory,
and list the .R scripts using
list.files.Then in a loop through the file names of your R scripts using
lapply,readLinesinto an objectgsubpatterns with function names and prefix them with package names and the colons in aforloopwriteLinesto the .R scripts (I prefixed them with'changed_'what should be easily removable but does not overwrite your original files, comment out the line if you are sure, otherwise itreturns only the text to be written)Notice, that this is dangerous and might overwrite your work without undo! Therefore, be sure to create a backup copy and practice with toy examples like this one.
Caveats: There are functions with the same name throughout the packages, e.g.
stats::filteranddplyr::filter, you should exclude them to not produce a mess. Also, if objects have the same names or parts, they might get prefixed as well, I tried to approach that by adding opening the parenthesis to the patterns.Data:
Store these lines in three separate .R scripts to reproduce: