2

I am trying to check if the package is run on Windows during the loading of the package and load some additional files. For some reason this doesn't work (added to my zzz.R):

.onLoad <- function(libname, pkgname){
    if(.Platform$OS.type == "windows") {
        # do specific task here
    }
}

How to make it work, is there a better way to do it?

Datageek
  • 25,977
  • 6
  • 66
  • 70

1 Answers1

1

EDIT to correct a wrong previous answer

After loading, loadNamespace looks for a hook function named .onLoad and calls it. The functions loadNamespace is usually called implicitly when library is used to load a package. However you can be useful at times to call these functions directly. So the following(essentially your code) works for me under windows platform.

.onLoad <- function(libname, pkgname ) {
    if(.Platform$OS.type == "windows")  print("windows")
    else print("others")
}

Then you test it using:

loadNamespace("loadpkg")
[1] "windows"
<environment: namespace:loadpkg>

Note also you can have the same thing using library, but you should unload the namespace before (I guess it checks if the package is already loaded and don't call all hooks):

unloadNamespace("loadpkg")
library("loadpkg")
[1] "windows"

don't use this , it is a wrong but accepted solution

You should initialize function parameters:

.onLoad <- function(libname = find.package(pkg_name), pkgname = pkg_name){
 if(.Platform$OS.type == "windows") {
    # do specific task here
  }
}
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • Thanks, do you mean I should replace pkg_name with the "myPackageName"? – Datageek Sep 25 '14 at 19:18
  • Huh? That's not how `.onLoad()` works and it's unlikely to fix the problem. – hadley Sep 26 '14 at 11:28
  • @hadley But here it works fine..How would you resolve the problem?Note that this use of `.onload` is used in many packages.. – agstudy Sep 26 '14 at 15:05
  • @agstudy Why does it fix the problem? Why do you think you should be supplying arguments to `.onLoad()`? I quickly skimmed 100 cran packages (https://github.com/search?p=5&q=user%3Acran+.onLoad&type=Code) and I didn't see any using `.onLoad()` that way. – hadley Sep 29 '14 at 14:14
  • @hadley you are right (see my edit here).thanks for the revision. I think it is a previous SO question that induce me in error, probably [this one](http://stackoverflow.com/questions/14926672/execute-a-function-from-package-after-doing-librarypkg). (you can maybe read the discussion there) – agstudy Sep 30 '14 at 05:28