Home > Net >  Is there an equivalent to using the double colon operator (::) with source() in R?
Is there an equivalent to using the double colon operator (::) with source() in R?

Time:01-06

Since my project contains a lot of different files that just contain function definitions (which I then source() in a main workflow file), I can often forget exactly which function is contained in which file.

This wouldn't be a problem if I could use my sourced files like packages with a syntax like this: source("file.r")::function(). Of course, that code returns an error (Error: unexpected '::' in "source("file.r")::"), but I'm hoping there is an equivalent operator I can use for sourced files.

CodePudding user response:

You can use environments to effect this, using $ in lieu of ::.

If you have files:

  • file1.R

    func1 <- function(x) x   1
    func2 <- function(y) y   2
    
  • file2.R

    func3 <- function(x) x   3
    func4 <- function(y) y   4
    

then you can create environments for them and load them into there with local=:

e1 <- new.env()
source("file1.R", local = e1)
e2 <- new.env()
source("file2.R", local = e2)
ls()
# [1] "e1" "e2"
e1$func1(1)
# [1] 2
e1$func2(1)
# [1] 3
e2$func3(1)
# [1] 4
e2$func4(1)
# [1] 5

Note: functions defined in file2.R will not "see" functions in file1.R. This has some pros and cons:

  • Pro: namespace pollution is reduced. If you have constants defined in a file that the functions within it must be able to reference, then this works well. Those constants are in a sense "private" (very loosely speaking) to functions in that same file.

  • Con: unlike a "package", functions that must see each other must either be defined in the same file or must have another mechanism for determining where to find the other functions.

  •  Tags:  
  • Related