在dplyr链中使用table()

xvw2m8pv  于 2023-05-04  发布在  其他
关注(0)|答案(4)|浏览(178)

有人能解释一下为什么table()不能在dplyr-magrittr管道操作链中工作吗?下面是一个简单的reprex:

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

排序时出错。list(y):'x'对于'sort'必须是原子的。你有没有在列表上调用'sort'?
但这当然有效:

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
ajsxfq5m

ajsxfq5m1#

此行为是通过设计实现的: www.example.com
由于您没有自己的.,tibble仍然作为第一个参数传递,因此它实际上更像是

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

官方的Magrittr变通方法是使用花括号

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

vu8f3i0k2#

dplyr中的%>%运算符实际上是从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
khbbv19g

khbbv19g3#

使用with(table(...))的方法如下:

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

类似于我们可能会将%>%读为“然后”,我会将其读为“然后用该数据制作此表”。

r9f1avp5

r9f1avp54#

  • *Janitor包中的tabyl**函数可以很好地使用管道,是原生表函数的一个很好的替代品。
library(janitor)
#> Warning: package 'janitor' was built under R version 4.1.3
#> 
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#> 
#>     chisq.test, fisher.test
mtcars %>%   tabyl(cyl, gear)
#>  cyl  3 4 5
#>    4  1 8 2
#>    6  2 4 1
#>    8 12 0 2

创建于2023-05-03带有reprex v2.0.2

相关问题