简体   繁体   中英

Create a native pipe compatible table() function

I am looking to develop a tab(x, y) function or tab(x, y, d) (where d = data.frame) to replace this command:

d <- mtcars
d |> dplyr::select(cyl, vs) |> table()

I try:

d <- mtcars
tab <- function (x, y) {
  result <- table(x, y)
  result
}

Without pipe, it's ok:

tab(d$cyl, d$vs)

With native pipe it doesn't work:

d |> tab(cyl, vs)

But it works with exposition pipe ( %$% ) from the magrittr package

d %$% tab(cyl, vs)

How to adapt the function to work with the native pipe operator ( |> )?

It can work with the native pipe, one way is to create an anonymous function like:

(\(df){...})()

So you can have something like

d |> (\(df){
  
  with(df, tab(cyl, vs))
})()
   y
x    0  1
  4  1 10
  6  3  4
  8 14  0
tab <- function(d, x, y){
  eval(substitute(table(d$x, d$y)))
}

mtcars |> tab(cyl, vs)
   
     0  1
  4  1 10
  6  3  4
  8 14  0

We could use tabyl from janitor

library(janitor)
d |> 
   tabyl(cyl, vs)

-output

 cyl  0  1
   4  1 10
   6  3  4
   8 14  0

In the dplyr framework you can embrace function arguments:

tab <- function(d, x, y) {
    select(d, {{x}}, {{y}}) |>
        table()
}

mtcars |> tab(cyl, vs)
##>    vs
##> cyl  0  1
##>   4  1 10
##>   6  3  4
##>   8 14  0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM