r - 在 summarise_at() 中使用 n() 时出错
问题描述
在 summarise_at() 中使用 n() 时,我收到此错误:
Error: n() should only be called in a data context
Call `rlang::last_error()` to see a backtrace
其他人认为这可能是dplyr
with的掩蔽问题plyr
,两种解决方案是:
- 替换
summarise_at()
为 `dplyr::summarise_at()' - 称呼
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()
内对数据源本身起作用,所以不是矢量化函数。只需用作矢量化版本。mutate
filter
summarize
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))
推荐阅读
- reactjs - 有没有办法在导航器中打开单个屏幕作为反应原生的模式?
- ruby-on-rails - 正确形成 API 请求
- c# - 每次用户在 DropDownMenu 中选择新项目时动态更改报告
- jquery - 无法向控制器发出 ajax 发布请求
- python - 如何在python中分离列表中的不同元素并将它们放入新列表中
- html - 如何制作图像中的html表格
- javascript - 不断从新的 Promise 获得未定义的结果
- python - 分类器损失函数维度超出范围错误
- python - 如何在 Windows python 3.6 中升级 dlib python 包
- c++ - 这是 ubuntu 16.04 中的 gdb 错误吗?