R and package masking – a real life example

by Silvia Bordogna

facebooktwittergoogle_pluspinterestlinkedintumblr

Very often, in our coding life, we forget one very simple yet important point to take care to: the importance of conflicts between packages.

When you load a library in best case the command line is executed with no problem. However, the console is sometimes stuffed with red messages that we often ignore, moreover when the function we need reach the desired goal.

Sooner or later during your R-user life you could stack in an error, and you could get crazy because you are sure of the accuracy of data, parameters and everything else.

The problem is exactly the upload of two or more packages that conflicts because they share the same name for different functions, that cannot be used by R simultaneously.

I bring you an example of a situation I faced working on a Shiny App that uses the following libraries at the top of the script:

The procedure was taking data from an Excel file with a command like this:

Then, with downloadHandler(), the App should provide the final results in .xlsx extensions too. These lines should complete the task:

 

Unfortunately the script crashes and the console shows the following error referring to the command

loadWorkbook(fname,create=TRUE) . The error was:

The reason why this happens is connected exactly to the fact that xlsx e XLConnect are in conflict, in fact, if you pay attention when they are loaded simultaneously, you get this message specifying the functions shared by both of them.

Lesson Learned: remember that the priority belongs to the last library loaded, hence, in this example, xlsx masks some function of XLConnect and cause the error.

A possible solution is loading each package every time you use it rigth above the connected commads, thus you avoid using functions with the syntax of the library that is not “in charge”.

Another solution is the “detach” command, a single command like “detach(“package:xlsx”, unload=TRUE)” can also solve your problems once and for all :)