Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding function name conflicts in R

I recently ran into a situation in which existing R code broke due the introduction of the dplyr library. Specifically, the lag function from the stats package, is being replaced by dplyr::lag. The problem is previously documented here, however no work around is provided. Research into R namespaces and environments leads to 2 possible solutions, neither very robust in my opinion:

  1. Make sure that package:stats appears first in the search() path so that lag resolves as the function in the stats package.
  2. Change all references of lag in my code to stats::lag

My question is whether either of these other solutions are possible:

  1. Loading the dplyr package in a way to force it to be in a "private" namespace in which its objects can only be accessed through the :: operator.
  2. A directive at library loading to force lag to resolve as stats::lag. This could be done either by removing dplyr::lag or overriding the search path (similar to the C++ using namespace::function directive.)
like image 980
mjreed Avatar asked Dec 21 '15 19:12

mjreed


1 Answers

you should consider library(conflicted) as it's designed for exactly this problem.
https://cran.r-project.org/web/packages/conflicted/index.html

putting conflicted::conflict_prefer(name = "lag", winner = "stats") after you load your packages ensures that anytime the function lag() is called in your script, it will use the stats function by default.

like image 198
CourtesyBus Avatar answered Nov 05 '22 08:11

CourtesyBus