首页 > 解决方案 > dplyr 的 n_distinct() 函数如何在内部工作?

问题描述

我喜欢 R 中可用的 dplyr 包,因为它的语法清晰且简单。我在零售领域,经常使用同一个包中的 n_distinct() 函数。我想知道 n_distinct() 函数如何在内部工作以计算唯一元素的长度?

我试图通过在 R-console 中键入函数的名称来做到这一点。它给了我以下输出:

>n_distinct()
function (..., na.rm = FALSE) 
{
    n_distinct_multi(list(...), na.rm)
}
<bytecode: 0x000000000766eee8>
<environment: namespace:dplyr>

它似乎在内部使用 n_distinct_multi() 函数。但我没有得到这个函数的任何代码:

>n_distinct_multi
Error: object 'n_distinct_multi' not found
> dplyr:: n_distinct_multi
Error: 'n_distinct_multi' is not an exported object from 'namespace:dplyr'
>? n_distinct_multi
No documentation for ‘n_distinct_multi’ in specified packages and libraries:
you could try ‘??n_distinct_multi’

请告诉我如何得到它在内部做什么?

标签: rdplyr

解决方案


感谢@caldwellst 和@Rui Barradas 的评论,您的两个解决方案都运行良好。我发布这个答案是为了帮助那些对 R 中的内部函数一无所知的人。“内部函数可以被同一个包的其他函数使用,但不能直接从 R-console 调用。调用内部函数,您应该使用 ::: 运算符以及包名称。”

例如,n_distinct_multi() 是 dplyr 包中的一个内部函数,由 n_distinct() 函数调用以查找给定向量中唯一值的长度。

要清楚

> library(dplyr)
> n_distinct
function (..., na.rm = FALSE) 
{
    n_distinct_multi(list(...), na.rm)
}
<bytecode: 0x000000000766eee8>
<environment: namespace:dplyr>

> n_distinct_multi
Error: object 'n_distinct_multi' not found

> dplyr:::n_distinct_multi
function (variables, na_rm = FALSE) 
{
    .Call(`_dplyr_n_distinct_multi`, variables, na_rm)
}
<bytecode: 0x000000000943eda8>
<environment: namespace:dplyr>

其中 _dplyr_n_distinct_multi() 是来自 C/C++ 库的编译函数。您可以使用 n_distinct_multi() 函数来查找向量的唯一值的长度,如下所示:

> dplyr:::n_distinct_multi(list(c(1:10,10)))
[1] 10

您还可以使用 getAnywhere() 查看内部函数的代码。

> library(dplyr)
> getAnywhere('n_distinct_multi')
A single object matching ‘n_distinct_multi’ was found
It was found in the following places
  namespace:dplyr
with value

function (variables, na_rm = FALSE) 
{
    .Call(`_dplyr_n_distinct_multi`, variables, na_rm)
}
<bytecode: 0x000000000943eda8>
<environment: namespace:dplyr>

推荐阅读