首页 > 解决方案 > 在 summarise_at() 中使用 n() 时出错

问题描述

在 summarise_at() 中使用 n() 时,我收到此错误:

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

其他人认为这可能是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()))

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

标签: rdplyrrlangsummarize

解决方案


我相信这是因为在,或n()内对数据源本身起作用,所以不是矢量化函数。只需用作矢量化版本。mutatefiltersummarizelength

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))

推荐阅读