[R] How to export a function from a package and access it only by specifying the namespace?

Henric (Nilsson) Winell nilsson.henric at gmail.com
Thu Dec 3 13:01:21 CET 2009


On 2009-12-02 16:31, Peng Yu wrote:
> On Tue, Dec 1, 2009 at 11:27 PM, Sharpie <chuck at sharpsteen.net> wrote:
>>
>> Peng Yu wrote:
>>> Then I try the package 'try.package' in an R session. I'm wondering
>>> why neither 'my_test_f' and 'try.package::my_test_f' work.
>>>
>> The error message you got below clearly explains this-- you did not export
>> my_test_f in your NAMESPACE file.  To access unexported functions, you must
>> use the ':::' operator:
>>
>>  try.package:::my_test_f()
>>
>>
>>
>> Peng Yu wrote:
>>> Why 'my_test_g' can be accessed with 'try.package::' and without
>>> 'try.package::'?
>>>
>> Because you exported it in the NAMESPACE file.
>>
>>
>>
>> Peng Yu wrote:
>>> Is there a way to make  'my_test_g' accessible only by specifying the
>>> namespace 'try.package::'?
>>>
>> No.
>>
>> The purpose of the '::' operator is for those cases where multiple packages
>> are loaded that each export a function with the same name.  This is known as
>> "masking" and the last loaded package will contribute the dominant
>> function-- i.e. the function the gets called when the user types
>> "functionName()" and not "packageName::functionName()".  The "::" operator
>> allows the selection of functions that are masked by the dominant function.
>>
>> If you really want to conceal a function from user-level code, don't export
>> it and it will only be accessible via the ":::" operator.
> 
> Is there a way to list all the functions in a namespace? I tried the
> following one, but it is not working.
> 
>> showMethods(where=getNamespace('try.package'))
> No applicable functions

You're almost there, and the above approach *is* working but only for S4 
methods. Try

showMethods(where = e <- getNamespace('stats4'))

I don't think there's a direct analogue for S3, but it that case you only do

ls(e)


HTH,
Henric



> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list