Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

r - dplyr::n() returns "Error: This function should not be called directly"

If I do:

dplyr::mutate(MeanValue = mean(RSSI), ReadCount = n())

everything works fine. But when I try to qualify the function:

dplyr::mutate(MeanValue = mean(RSSI), ReadCount = dplyr::n())

I get the error mentioned in the title.

So, I do not really have a problem, I can just avoid doing that, but I'm curious about why it even happens. I already looked at another question (dplyr: "Error in n(): function should not be called directly"), but as far as I know, dplyr is the only library I'm using. I tried doing what the answer suggests anyway, but

detach(package:plyr)

results in

Error in detach(package:plyr) : invalid 'name' argument and

conflicts()

does not mention n():

[1] "filter" "lag" "body<-" "intersect" "kronecker" "setdiff" "setequal" "union"
, most of which is cause by dplyr.

I guess I'm not the only one confused by this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...