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

Ali*_*Ali 1 r dplyr summarize rlang

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

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

其他人认为这可能是dplyrwith 的掩盖问题plyr,两个解决方案是:

  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()))
Run Code Online (Sandbox Code Playgroud)

注意:如果删除count = n()该代码,运行不会出现任何问题

cal*_*lst 5

我相信这是因为n()内的数据源本身的作品mutatefilter或者summarize,所以不是一个矢量化功能。只需将其length用作矢量化版本即可。

Df %>% 
  group_by(Condition) %>% 
  summarise_at(vars(one_of(x)), c(mean = mean, sd = sd, count = length))
Run Code Online (Sandbox Code Playgroud)

如果只希望有一个计数列,则:

Df %>% 
  group_by(Condition) %>%
  mutate(count = n()) %>%
  group_by(Condition, count) %>%
  summarise_at(vars(one_of(x)), c(mean = mean, sd = sd))
Run Code Online (Sandbox Code Playgroud)