Search code examples
rpipemagrittrsummarytools

Does ctable in R not work with native pipes?


I am seeing a quirk with the ctable() function from R summarytools package and trying to see if I'm missing something here.

The ctable introduction vignette states "Pipe operators from magrittr (%>%, %$%) and pipeR (%>>%) are fully supported; the native |> introduced in R 4.0 is supported as well."

Using the native pipe works as expected for the freq() and descr() functions.

However, I'm having trouble with the native pipe for ctable(). If I use the native pipe, I receive an Error: object 'ObjectName' not found were ObjectName is one of the variables in the ctable() function. It does not work with the regular magrittr pipe. Yet, ctable() does work if I switch to the magrittr exposion pipe %$%. I haven't found a difference if I add the x= and y= argument specifications.

Yet another quirk in this mess is that ctable() does work with a native pipe IF I reduce the data frame by selecting only the two columns I want for the ctable(). However, I have to remove the column names from the ctable() in this case, else I receive an error; also, the column names that print in the results look awful & are not useful.

Am I missing something here? Shouldn't ctable() work the same as freq() or descr() when using the native pipe or regular magrittr pipe?

For those curious why my examples have the as.factor(), as far as I know, ctable() still has the PrettyNum issue when using numeric values -- see Dominic Comtois' Github and this SO post.

Reproducible examples

# setup
library(summarytools)
library(magrittr)
library(dplyr)
data("mtcars")

# these work just fine as expected
freq(mtcars$cyl)
mtcars |> freq(cyl)
mtcars |> descr(qsec)
mtcars |> subset(select=c(qsec, hp)) |> descr()

# ctable not working with the native pipe or regular magrittr pipe
mtcars |>
  mutate(cyl = as.factor(cyl), gear = as.factor(gear)) |> 
  # mutate(cyl = as.factor(cyl), gear = as.factor(gear)) %>%
  ctable(cyl, gear)

# ctable works with the exposion pipe
mtcars |>
  mutate(cyl = as.factor(cyl), gear = as.factor(gear)) %$%
  ctable(cyl, gear)

# ctable works with native pipe if also selecting to only the columns for ctable, but output looks off
mtcars |>
  mutate(cyl = as.factor(cyl), gear = as.factor(gear)) |> 
  select(cyl, gear) |> 
  # ctable(cyl, gear)  # gives error
  ctable()  # no error

Solution

  • |> inserts the left hand side into the first argument of the right hand side (or the _ argument position if specified) but there is no argument in ctable that is documented to accept a data frame. Use with with either pipe (|> or %>%):

    library(dplyr)
    library(summarytools)
    
    mtcars |>
      mutate(cyl = as.factor(cyl), gear = as.factor(gear)) |>
      with(ctable(cyl, gear))