crosstab: Create a Crosstab

View source: R/data.frame.R

crosstabR Documentation

Create a Crosstab

Description

Transform a data set into an n x m table, e.g. to be used in certestats::confusion_matrix().

Usage

crosstab(
  df,
  identifier,
  compare,
  outcome,
  positive = "^pos.*",
  negative = "^neg.*",
  ...,
  na.rm = TRUE,
  ignore_case = TRUE
)

Arguments

df

a data.frame

identifier

a column name to use as identifier, such as a patient ID or an order ID

compare

a column name for the two axes of the table: the labels between the outcomes must be compared

outcome

a column name containing the outcome values to compare

positive

a regex to match the values in outcome that must be considered as the Positive class, use FALSE to not use a Positive class

negative

a regex to match the values in outcome that must be considered as the Negative class, use FALSE to not use a Negative class

...

manual regexes for classes if not using positive and negative, such as ⁠Class1 = "c1", Class2 = "c2", Class3 = "c3"⁠

na.rm

a logical to indicate whether empty values must be removed before forming the table

ignore_case

a logical to indicate whether the case in the values of positive, negative and ... must be ignored

Examples

df <- data.frame(
  order_nr = sort(rep(LETTERS[1:20], 2)),
  test_type = rep(c("Culture", "PCR"), 20),
  result = sample(c("pos", "neg"),
                  size = 40,
                  replace = TRUE,
                  prob = c(0.3, 0.9))
)
head(df)

out <- df |> crosstab(order_nr, test_type, result)
out


df$result <- gsub("pos", "#p", df$result)
df$result <- gsub("neg", "#n", df$result)
head(df)
# gives a warning that pattern matching failed:
df |> crosstab(order_nr, test_type, result)

# define the pattern yourself in such case:
df |> crosstab(order_nr, test_type, result,
               positive = "#p",
               negative = "#n")
                             
                             
# defining classes manually, can be more than 2:
df |> crosstab(order_nr, test_type, result,
               ClassA = "#p", Hello = "#n")
                             
if ("certestats" %in% rownames(utils::installed.packages())) {
  certestats::confusion_matrix(out)
}

certe-medical-epidemiology/certetoolbox documentation built on April 17, 2025, 3:24 a.m.