【问题标题】:Got an error when using increment variable name inside dplyr在 dplyr 中使用增量变量名称时出错
【发布时间】:2020-04-08 06:50:22
【问题描述】:

运行代码时出现以下错误:“错误:列col 未知”。

for (col in names(test)) {

final  <-  test  %>% 
  group_by(col, "DT") %>%
  summarise(n = n())  
}

测试数据集如下所示:

col 应该是 transactionId,然后是 Product,并且每次我使用 DT 创建频率表时:transactionIdDT, ProductDT

谢谢

【问题讨论】:

  • 什么是“DT”?您能否添加一个可重现的示例并显示相同的预期输出?
  • 我加了一个数据和例子

标签: r for-loop dplyr


【解决方案1】:

通常,最好以长格式获取数据,以避免使用for 循环。我们可以使用count,这是group_by + summarise的快捷方式

library(dplyr)

test %>%
  mutate_all(as.character) %>%
  tidyr::pivot_longer(cols = -DT) %>%
  count(DT, value)

【讨论】:

  • 我收到一个错误:计数错误(., DT, value) : object 'DT' not found
  • @Alexey DT 是您在数据中的列名。如果它不起作用,请使用dput 分享一个可重现的示例,而不是图像。见here on how to give a reproducible example
猜你喜欢
  • 1970-01-01
  • 2014-11-18
  • 2022-01-13
  • 2020-10-16
  • 1970-01-01
  • 1970-01-01
  • 2018-09-13
  • 2019-01-27
  • 2021-10-02
相关资源
最近更新 更多