I'm trying to understand how this package (darksky
, found here: https://github.com/hrbrmstr/darksky) works.
It contains these two scripts in the R folder:
aaa.R
, andget-current-forecast.R
The former (aaa.R
) contains a subfunction called convert_time
. This is being called by the latter (get-current-forecast.R
) and seems to work but aaa.R
is not imported/refferred to by get-current-forecast.R
.
How is this working? Are all subfunctions available to other functions in the same package?
Packages don't work the same as sourcing R files in an interactive session. All the functions defined in every .R file in a package are registered in the package's namespace, which gets attached when you run library(foo)
. So when a function in the package calls some other function, R first looks in that package's namespace for function by that name.
However, functions defined inside another function are different. R won't see and register those in the package namespace. They would be available only within the enclosing function.
For example,
foo <- function(x){
y <- x+1
bar <- function(z){
z+1
}
bar(y)
}
If foo
were defined in some .R file in a package, the function foo
would be visible, but bar
would be visible only within foo
.