Rob*_*les 5 r pipe dplyr magrittr
有人可以解释为什么table()在dplyr-magrittr管道操作链中不起作用?这是一个简单的代表:
tibble(
type = c("Fast", "Slow", "Fast", "Fast", "Slow"),
colour = c("Blue", "Blue", "Red", "Red", "Red")
) %>% table(.$type, .$colour)
Run Code Online (Sandbox Code Playgroud)
sort.list(y)出错:'x'必须是'sort.list'的原子'你有没有在列表上调用'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
Run Code Online (Sandbox Code Playgroud)
MrF*_*ick 11
此行为是设计使然:https://github.com/tidyverse/magrittr/blob/00a1fe3305a4914d7c9714fba78fd5f03f70f51e/README.md#re-using-the-placeholder-for-attributes
既然你没有.它自己,那么仍然会将tibble作为第一个参数传递,所以它更像是
... %>% table(., .$type, .$colour)
Run Code Online (Sandbox Code Playgroud)
官方的magrittr解决方案是使用花括号
... %>% {table(.$type, .$colour)}
Run Code Online (Sandbox Code Playgroud)
我已经习惯with(table(...))这样使用:
tibble(type = c("Fast", "Slow", "Fast", "Fast", "Slow"),
colour = c("Blue", "Blue", "Red", "Red", "Red")) %>%
with(table(type, colour))
Run Code Online (Sandbox Code Playgroud)
类似于我们读作%>%“然后”的方式,我将其读作“然后用该数据制作这个表”。
该%>%运营商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)
Run Code Online (Sandbox Code Playgroud)
输出:
colour
type Blue Red
Fast 1 2
Slow 1 1
Run Code Online (Sandbox Code Playgroud)