Basic Usage

Unused factor levels

crosstabr by default preserves unused factor levels. This might be useful when conducting exploratory tasks -- it would probably bad to miss levels which were simply not observed.

library(crosstabr)
test_dat <- titanic # need to export data
index <- test_dat$Class == "2nd"
test_dat[index, ] <- NA

test_dat %>%
  crosstab(Survived ~ Class)

If you want to remove unused levels, simply add droplevels = FALSE when setting up the layout:

test_dat %>%
  crosstab(Survived ~ Class) %>%
  layout_column(droplevels = T)

Programming with crosstabr

You can program with crosstabr in several ways.

Wrapping the pipeline

In case you want to reuse a certain configuration of using crosstabr, you can simplay wrap it in a function:

fun <- function(data, formula) {
  data %>%
    crosstab(formula) %>% 
    layout_column() %>% 
    add_stats(chisq.test)
}

fun(titanic, Survived ~ Class)

Creating formula from (string) variables

In case you want to refer to the names of variables via a string variable, you can use reformulate to construct the formula for you:

fun2 <- function(data, dep, indep) {
  data %>%
    crosstab(reformulate(indep, response = dep))
}

dep <- "Survived"
indep <- "Class"

fun2(titanic, dep, indep)


tklebel/crosstabr documentation built on May 31, 2019, 3:43 p.m.