I have encountered some rather strange behavior from R. I tested it on Windows and Ubuntu with the same results.
So let's assume I have a package called QS1API
with the following substructure:
.
├── DESCRIPTION
├── man
├── NAMESPACE
├── QS1API.Rproj
├── R
│ ├── class-API.R
│ └── QS1API.R
The class-API.R
includes the definition of a class called API
:
.API <- methods::setRefClass(
Class = ".API"
)
#' @export
API <- function(...) {
tmpObj <- methods::new(".API", ...)
return(tmpObj)
}
.API$methods(
print_name = function() {
cat("Hey it is QS1")
}
)
Now I have a package called QS2API
with the following substructure:
.
├── DESCRIPTION
├── man
├── NAMESPACE
├── QS2API.Rproj
├── R
│ ├── class-API.R
│ └── QS2API.R
This package also exports a class with the name, i.e. API
, however, its print_name
function is different:
.API <- methods::setRefClass(
Class = ".API"
)
#' @export
API <- function(...) {
tmpObj <- methods::new(".API", ...)
return(tmpObj)
}
.API$methods(
print_name = function() {
cat("Hey it is QS2")
}
)
Here comes the strange part! If I access the print_name
function in different sessions, all good:
QS1API::API()$print_name
Class method definition for method print_name()
function ()
{
cat("Hey it is QS1")
}
<environment: 0x55c369046158>
New Session:
QS2API::API()$print_name
Class method definition for method print_name()
function ()
{
cat("Hey it is QS2")
}
<environment: 0x559ab67de3e8>
But when I use the same session, the namespace of the class seems to be totally ignored:
QS1API::API()$print_name
Class method definition for method print_name()
function ()
{
cat("Hey it is QS1")
}
<environment: 0x558badba26c0>
QS2API::API()$print_name
Class method definition for method print_name()
function ()
{
cat("Hey it is QS1")
}
<environment: 0x558bae0858a8>
> api <- QS1API::API()
> class(api)
[1] ".API"
attr(,"package")
[1] "QS1API"
> api2 <- QS2API::API()
> class(api2)
[1] ".API"
attr(,"package")
[1] "QS1API"
This is so confusing...
Actually, isn't that exactly why the namespace should be written in front of functions/classes? What is going on here?