So, I do not really have a problem, I can just avoid [writing dplyr::n()
], but I'm curious about why it even happens.
Here's the source code for dplyr::n
in dplyr 0.5.0:
function () {
stop("This function should not be called directly")
}
That's why the fully qualified form raises this error: the function always returns an error. (My guess is that the error-throwing function dplyr::n
exists so that n()
could have a typical documentation page with examples.)
Inside of filter
/mutate
/summarise
statements, n()
is not calling this function. Instead, some internal function calculates the group sizes for the expression n()
. That's why the following works when dplyr is not loaded:
n()
#> Error: could not find function "n"
library(magrittr)
iris %>%
dplyr::group_by(Species) %>%
dplyr::summarise(n = n())
#> # A tibble: 3 × 2
#> Species n
#> <fctr> <int>
#> 1 setosa 50
#> 2 versicolor 50
#> 3 virginica 50
Here n()
cannot be mapped to a function, so we get an error. But when used it inside of a dplyr verb, n()
does map to something and returns group sizes.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…