help(unique)
shows that unique
function is present in two packages - base
and data.table
. I would like to use this function from data.table
package. I thought that the following syntax - data <- data.table::unique(data)
indicates the package to be used. But I get the following error -
'unique' is not an exported object from 'namespace:data.table'
But data <- unique(data)
works well.
What is wrong here?
There are actually two infix operators in R that pull functions from particular package namespaces. You used
::
but there is also a:::
that retrieves "unexported" functions. Theunique
-function is actually a family of functions and its behavior will depend on both the class of its argument and the particular packages that have been loaded. The R term of this is "generic". Try:The other tool that lets you peek behind the curtain that the lack of "exportation" is creating is the
getAnywhere
-function. It lets you see the code at the console:The function in question is really
unique.data.table
, an S3 method defined in thedata.table
package. That method is not really intended to be called directly, so it isn't exported. This is typically the case with S3 methods. Instead, the package registers the method as an S3 method, which then allows the S3 generic,base::unique
in this case, to dispatch on it. So the right way to call the function is:We use
base::unique
, which is exported, and it dispatchesdata.table:::unique.data.table
, which is not exported. The functiondata.table:::unique
does not actually exist (or does it need to).As eddi points out,
base::unique
dispatches based on the class of the object called. Sobase::unique
will calldata.table:::unique.data.table
only if the object is adata.table
. You can force a call to that method directly with something likedata.table:::unique.data.table(iris)
, but internally that will mostly likely result in the next method getting called unless your object is actually adata.table
.