在 summarise_at() 中使用 n() 时出错

Error while using n() inside summarise_at()

在 summarise_at() 中使用 n() 时,出现此错误:

Error: n() should only be called in a data context
Call `rlang::last_error()` to see a backtrace

其他人认为这可能是 dplyrplyr 的屏蔽问题,两个解决方案是:

  1. summarise_at()替换为`dplyr::summarise_at()'
  2. 致电detach("package:plyr", unload=TRUE)

都没有消除这个错误,我很想知道是什么导致了它。这是一个可重现的示例,它应该会导致相同的错误:

Df <- data.frame(
  Condition = c(rep("No", 20), rep("Yes",20)),
  Height = c(rep(1,10),rep(2,10),rep(1,10),rep(2,10)),
  Weight = c(rep(10,5),rep(20,5),rep(30,5), rep(40,5))
)

x <- c("Height","Weight")

Df %>% 
  group_by(Condition) %>% 
  summarise_at(vars(one_of(x)), c(mean = mean, sd = sd, count = n()))

注意:如果您删除 count = n(),代码运行没有任何问题

我认为这是因为 n()mutatefiltersummarize 中处理数据源本身,所以不是矢量化函数。只需使用 length 作为矢量化版本。

Df %>% 
  group_by(Condition) %>% 
  summarise_at(vars(one_of(x)), c(mean = mean, sd = sd, count = length))

如果您只想拥有一个计数列,则:

Df %>% 
  group_by(Condition) %>%
  mutate(count = n()) %>%
  group_by(Condition, count) %>%
  summarise_at(vars(one_of(x)), c(mean = mean, sd = sd))