Search code examples
rpivot-tableapplysapply

How use crosstab with apply or sapply function


I am struggling with using the crosstab function, available at the link:

source("http://pcwww.liv.ac.uk/~william/R/crosstab.r")

I have also used the gtsummary library and converted mtcars to a tibble, then converted the vs and am columns to characters using:

library(gtsummary)
mtcars = mtcars %>% as_tibble()
mtcars = apply(mtcars %>% select(vs, am), 2, as.character)

crosstab(mtcars, row.vars = "vs")
crosstab(mtcars, row.vars = "am")

I would like to achieve the same using the apply or sapply function, without using the crosstab function's row.vars argument, which I do not know how to set.

I have tried

apply(mtcars, 2, crosstab(mtcars, row.vars = c('vs', 'am')))

But it does not work. Is there an alternative way to achieve this, even with the sapply function?

Thanks.


Solution

  • Hi you almost got it right, you just got confused with the apply syntax:

    You want to iterate over a list of column names (variables) instead of the dataframe and pass this as the row.vars argument.

    lapply(c('vs', 'am'),\(col) crosstab(mtcars, row.vars = col))
    sapply(c('vs', 'am'),\(col) crosstab(mtcars, row.vars = col),simplify = F)
    
    

    The equivalent for loop would be:

    for (col in c('vs', 'am')) {
      crosstab(mtcars,row.vars = col)|>print()
    }