【问题标题】:Using table() in dplyr chain在 dplyr 链中使用 table()
【发布时间】:2017-11-15 15:01:30
【问题描述】:

有人可以解释为什么table()在 dplyr-magrittr 管道操作链中不起作用吗?这是一个简单的表示:

tibble(
  type = c("Fast", "Slow", "Fast", "Fast", "Slow"),
  colour = c("Blue", "Blue", "Red", "Red", "Red")
) %>% table(.$type, .$colour)

sort.list(y) 中的错误:对于“sort.list”,“x”必须是原子的 您是否在列表中调用了“排序”?

但这当然有效:

df <- tibble(
  type = c("Fast", "Slow", "Fast", "Fast", "Slow"),
  colour = c("Blue", "Blue", "Red", "Red", "Red")
) 

table(df$type, df$colour)


       Blue Red
  Fast    1   2
  Slow    1   1

【问题讨论】:

  • 你也可以使用df %&gt;% group_by(type, colour) %&gt;% tally()
  • 您也可以使用df %&gt;% select(type,colour) %&gt;% tableselect 以防万一您有其他列)。

标签: r pipe dplyr magrittr


【解决方案1】:

dplyr 中的%&gt;% 运算符实际上是从magrittr 导入的。使用magrittr,我们还可以使用%$% 运算符,它公开了前一个表达式中的名称:

library(tidyverse)
library(magrittr)

tibble(
  type = c("Fast", "Slow", "Fast", "Fast", "Slow"),
  colour = c("Blue", "Blue", "Red", "Red", "Red")
) %$% table(type, colour)

输出:

      colour
type   Blue Red
  Fast    1   2
  Slow    1   1

【讨论】:

    【解决方案2】:

    我已经习惯像这样使用with(table(...))

    tibble(type = c("Fast", "Slow", "Fast", "Fast", "Slow"),
           colour = c("Blue", "Blue", "Red", "Red", "Red")) %>% 
      with(table(type, colour))
    

    类似于我们可能将%&gt;% 解读为“然后”的方式,我会将其解读为“然后使用该数据制作此表”。

    【讨论】:

      【解决方案3】:

      这种行为是设计使然:https://github.com/tidyverse/magrittr/blob/00a1fe3305a4914d7c9714fba78fd5f03f70f51e/README.md#re-using-the-placeholder-for-attributes

      由于您自己没有.,因此 tibble 仍然作为第一个参数传递,所以它真的更像

      ... %>% table(., .$type, .$colour)
      

      官方的 magrittr 解决方法是使用花括号

      ... %>% {table(.$type, .$colour)}
      

      【讨论】:

      • 啊!与我在管道上遇到的另一个问题相同,所以 (stackoverflow.com/questions/44007998/…)。看来我学得很慢。谢谢!
      • 我认为使用do 也可以解决问题...我想这是因为table 的输出不是数据框,所以像df %&gt;% do(as.data.frame(table(.$type, .$colour))) 这样看起来很糟糕
      猜你喜欢
      • 2014-11-13
      • 2017-11-25
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 2017-10-15
      • 2020-05-21
      相关资源
      最近更新 更多