On 13/10/2016 4:18 AM, g.maub...@weinwolf.de wrote:
Hi All,

in my R programs I use different libraries to work with Excel sheets, i.
e. xlsx, excel.link.

When running chunks of code repeatedly and not always in the order the
program should run for development purposes I ran into trouble. There were
conflicts between the methods within these functions causing R to crash.

I thought about defining functions for the different task and calling the
libraries locally to there functions. Doing this test

-- cut --

f_test <- function() {
    cat("Loaded packages AFTER loading library")

cat("Loaded packages BEFORE function call ----------------------------")


cat("Loaded packages AFTER function call -----------------------------")

-- cut --

showed that the library "xlsx" was loaded into the global environment and
stayed there although I had expected R to unload the library when leaving
the function. Thus confilics can occur more often.

I had a look into ?library and saw that there is no argument telling R to
hold the library in the calling environment.

How can I load libraries locally to the calling functions?

You can detach at the end of your function, but that's tricky to get right: the package might have been on the search list before your function was called. It's better not to touch the search list at all.

The best solution is to use :: notation to get functions without putting them on the search list. For example, use

xlsx::write.xlsx(data, file)

If you are not sure if your user has xlsx installed, you can use requireNamespace() to check.

Duncan Murdoch

R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to