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 (|>
)?
CodePudding user response:
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
CodePudding user response:
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