Home > Mobile >  How to create a pipeable table function?
How to create a pipeable table function?

Time:11-06

The table function takes vectors as arguments. For example:

table(mtcars$cyl, mtcars$am)

     0  1
  4  3  8
  6  4  3
  8 12  2

I tried converting this into a pipeable function by passing data as the first argument and using that inside my function within the table function.

tab_fun <- function(data, x, y) {
  table(data$x, data$y)
}

But when I run my function, I get this error...

tab_fun(mtcars, cyl, am)

< table of extent 0 x 0 >

I'm trying to figure out what's happening. Is there a way to create a function like this, or are there already functions that do this same thing?

CodePudding user response:

Another option:

library(tidyverse)

tab_fun <- function(data, x, y){
 summarise(data, tab = list(table({{x}}, {{y}})))$tab[[1]]
}

tab_fun(mtcars, cyl, am)
#>    
#>      0  1
#>   4  3  8
#>   6  4  3
#>   8 12  2

CodePudding user response:

Base R deparse(substitute(...)) may be one approach.

tab_fun <- function(data, x, y) {
  table(data[, deparse(substitute(x))], data[, deparse(substitute(y))])
}

tab_fun(mtcars, cyl, am)

# or in a piped workflow:

mtcars |> 
  tab_fun(cyl, am)

#>    
#>      0  1
#>   4  3  8
#>   6  4  3
#>   8 12  2

Created on 2022-11-05 with reprex v2.0.2

  •  Tags:  
  • r
  • Related