为什么`data.table :: unique`不工作? [英] Why `data.table::unique` doesn't work?
问题描述
help(unique)
显示唯一
函数存在于两个软件包中 - base
和 data.table
。我想从 data.table
包中使用此函数。我认为下面的语法 - data< - data.table :: unique(data)
表示要使用的包。但我收到以下错误 -
'unique'不是'namespace:data.table'中的导出对象
但 data< - unique(data)
b
这里有什么问题?
unique.data.table 是在 data.table
包中定义的S3方法。这种方法并不是真正意在被直接调用,所以它不会被导出。这通常是S3方法的情况。相反,包将方法注册为S3方法,然后允许S3通用 base :: unique
在这种情况下调度它。因此,调用函数的正确方法是:
library(data.table)
irisDT< - data。表(iris)
unique(irisDT)
我们使用 base :: unique
,它被导出,并且分派 data.table ::: unique.data.table
,它不导出。函数 data.table ::: unique
实际上不存在(或者它需要)。
eddi指出, base :: unique
基于调用的对象的类调度。因此 base :: unique
只有在对象是一个对象时才会调用 data.table ::: unique.data.table
data.table
。你可以直接使用 data.table ::: unique.data.table(iris)
强制调用该方法,但在内部,很可能会导致下一个方法得到调用,除非你的对象实际上是一个 data.table
。
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?
The function in question is really unique.data.table
, an S3 method defined in the data.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:
library(data.table)
irisDT <- data.table(iris)
unique(irisDT)
We use base::unique
, which is exported, and it dispatches data.table:::unique.data.table
, which is not exported. The function data.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. So base::unique
will call data.table:::unique.data.table
only if the object is a data.table
. You can force a call to that method directly with something like data.table:::unique.data.table(iris)
, but internally that will mostly likely result in the next method getting called unless your object is actually a data.table
.
这篇关于为什么`data.table :: unique`不工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!