Dplyr: “错误在 n() : 函数不应该被直接调用”

我试图复制 dplyr 包中的一个示例,但是得到了这个错误消息。我希望看到一个新的列 n 与每个组合的频率生产。我错过了什么?我再三检查过包裹是否装好了。

 library(dplyr)
# summarise peels off a single layer of grouping
by_vs_am <- group_by(mtcars, vs, am)


by_vs <- summarise(by_vs_am, n = n())

N ()中的错误: 不应该直接调用此函数

65869 次浏览

I presume you have dplyr and plyr loaded in the same session. dplyr is not plyr. ddply is not a function in the dplyr package.

Both dplyr and plyr have the functions summarise/summarize.

Look at the results of conflicts() to see masked objects.

As mentioned by the previous answer, you may have a conflict between plyr and dplyr. You can to run this command to unload the plyr package.

detach("package:plyr", unload=TRUE)

Then you can continue as expected.

library(dplyr)
...
summarise(n = n())

To avoid confusions with masking functions, it is clear to use the "package::function" specification, like example below:

delay <- dplyr::summarise(by_tailnum,
count = n(),
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE))

In another case, this error occurred in the following code.

library(dplyr) # dplyr 0.5.0
library(lazyeval)


df <- data_frame(group = c(1, 2, 2, 3, 3, 3))


g <- "group"


df %>%
group_by_(g) %>%
summarise_(
n = n(),
sum = interp(~sum(col, na.rm = TRUE), col = as.name(g))
)
# Error in n() : This function should not be called directly

It can be solved as follows.

df %>%
group_by_(g) %>%
summarise_(
n = "n()",
sum = interp(~sum(col, na.rm = TRUE), col = as.name(g))
)
# A tibble: 3 × 3
# group     n   sum
# <dbl> <int> <dbl>
# 1     1     1     1
# 2     2     2     4
# 3     3     3     9

Faced similar issue while executing code as per mentioned blog and then run solution in detach("package:plyr", unload=TRUE)

Blog : https://www.analyticsvidhya.com/blog/2017/09/comparative-stock-analysis/

Master_Data_AutoCorrelations<-Master_Data_lags %>%
gather(key = "lag", value = "lag_value", -c(Stock,Date, Close)) %>%
mutate(lag = str_sub(lag, start = 5) %>% as.numeric) %>%
group_by(Stock, lag) %>%
summarize(
cor = cor(x = Close, y = lag_value, use = "pairwise.complete.obs"),
cutoff_upper = 2/(n())^0.5,
cutoff_lower = -2/(n())^0.5
)

Post running detach,when above code was rerun it worked fine though received warning message as per below ,not sure whether plyr got unloaded or not.And how is the code executed properly ?

Warning message: ‘plyr’ namespace cannot be unloaded: namespace ‘plyr’ is imported by ‘reshape2’, ‘scales’, ‘broom’, ‘ggplot2’ so cannot be unloaded

for me the solution was detach() function I utilized that function down package