Reputation: 4145
If I have a function fun()
which requires another function, say, select()
from some other package (in this case dplyr
) saved in an R file helpfile.r and I want to use this function fun()
in another R file, I can simply source that function using source()
Now I noticed that when I use library(dplyr)
in helpfile.r and I source that file in my main file, the package gets loaded, however, all functions that have conflicts with other functions from other packages get ommited. In my case: I had already loaded the package MASS
which also has a select()
function that was still "active" after I loaded dplyr
in this way.
Question: Why doesnt the package that is loaded later in the chain overwrite the function from an earlier package, when I load a package via source()
?
Upvotes: 2
Views: 225
Reputation: 43
As @Jeremy pointed out above, explicitly stating the namespaces of the functions is always the safer option and is a good practice if you want to make your code more robust. The downside for this is that it makes your code harder to read for humans.
Alternatively, if you were to use a lot of functions from conflicting packages and want to avoid typing complete namespaces, you could use the box
package. With that you can attach the package library, but use local aliases easily for certain conflicting functions, e.g.
box::use(MASS[MASS_select = select, ...])
This code would replace the library()
function call.
Upvotes: 1
Reputation: 348
Packages mask each other in the order they are loaded. source()
is like executing the whole file with CTRL+SHIFT+S
or CTRL+A
followed by CTRL+ENTER
.
I'd recommend you to make your helpfile.r more standalone by not loading the whole package but writing out the complete namespace eg dyplr::select()
.
Upvotes: 2