## ----setup, include = FALSE---------------------------------------------------
# Vignettes use precomputed example data by default.
# To rebuild examples with live RxNorm/RxClass API calls, set:
# Sys.setenv(RXREF_BUILD_VIGNETTES_ONLINE = "true")

online_env <- identical(
  tolower(Sys.getenv("RXREF_BUILD_VIGNETTES_ONLINE")),
  "true"
)

has_net <- tryCatch({
  requireNamespace("curl", quietly = TRUE) && curl::has_internet()
}, error = function(e) FALSE)

run_live <- online_env && has_net

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

library(rxref)
library(dplyr)

read_rxref_example <- function(file) {
  path <- system.file("extdata", file, package = "rxref")
  if (!nzchar(path)) {
    stop(
      "The example data file '", file, "' was not found. ",
      "Reinstall rxref or rebuild the vignette with ",
      "RXREF_BUILD_VIGNETTES_ONLINE=true."
    )
  }
  readRDS(path)
}

## ----eval = FALSE-------------------------------------------------------------
# Sys.setenv(RXREF_BUILD_VIGNETTES_ONLINE = "true")

## ----define-------------------------------------------------------------------
beta_blocker_names <- c(
  "acebutolol",
  "atenolol",
  "betaxolol",
  "bisoprolol",
  "carvedilol",
  "labetalol",
  "metoprolol",
  "nadolol",
  "nebivolol",
  "penbutolol",
  "pindolol",
  "propranolol",
  "sotalol",
  "timolol"
)

## ----resolve------------------------------------------------------------------
if (run_live) {
  bb_ingredients <- find_ingredients(beta_blocker_names) |>
    filter(tty == "IN") |>
    distinct(
      input,
      ingredient_rxcui = rxcui,
      ingredient_name = name,
      ingredient_tty = tty
    )
} else {
  bb_ingredients <- read_rxref_example("bb_ingredients.rds")
}

bb_ingredients

## ----expand-------------------------------------------------------------------
if (run_live) {
  bb_products <- products_for_ingredients(
    bb_ingredients$ingredient_rxcui,
    ttys = product_ttys("default"),
    include_combos = TRUE,
    concept_status = "active"
  ) |>
    left_join(bb_ingredients, by = "ingredient_rxcui")
} else {
  bb_products <- read_rxref_example("bb_products.rds")
}

bb_products

## ----exclude-option-----------------------------------------------------------
if (run_live) {
  bb_single_ingredient_products <- products_for_ingredients(
    bb_ingredients$ingredient_rxcui,
    ttys = product_ttys("default"),
    include_combos = FALSE,
    concept_status = "active"
  ) |>
    left_join(bb_ingredients, by = "ingredient_rxcui")
} else {
  bb_single_ingredient_products <- read_rxref_example(
    "bb_single_ingredient_products.rds"
  )
}

bb_single_ingredient_products

## ----historical-products, eval = FALSE----------------------------------------
# bb_products_historical <- products_for_ingredients(
#   bb_ingredients$ingredient_rxcui,
#   ttys = product_ttys("default"),
#   include_combos = TRUE,
#   concept_status = "active_and_historical"
# )

## ----filtering-matters--------------------------------------------------------
if (run_live) {
  bb_attrs <- get_clinical_attributes(
    unique(bb_products$product_rxcui)
  ) |>
    rename(product_rxcui = rxcui)
} else {
  bb_attrs <- read_rxref_example("bb_attrs.rds")
}

bb_attrs |>
  count(route, dose_form_group, sort = TRUE)

## ----filter-------------------------------------------------------------------
if (run_live) {
  bb_oral_products <- bb_products |>
    filter_products_by_route(route = "ORAL")
} else {
  bb_oral_products <- read_rxref_example("bb_oral_products.rds")
}

bb_oral_products

## ----filter-summary-----------------------------------------------------------
bb_oral_products |>
  count(route, dose_form_group, sort = TRUE)

## ----map----------------------------------------------------------------------
if (run_live) {
  bb_oral_ndc_map <- map_rxcui_to_ndc(
    unique(bb_oral_products$product_rxcui),
    status = "ACTIVE"
  )

  bb_oral_ndcs <- bb_oral_ndc_map |>
    left_join(
      bb_oral_products,
      by = c("rxcui" = "product_rxcui")
    ) |>
    rename(
      product_rxcui = rxcui,
    ) |>
    distinct()
} else {
  bb_oral_ndcs <- read_rxref_example("bb_oral_ndcs.rds")
}

bb_oral_ndcs

## ----map-select---------------------------------------------------------------
bb_oral_ndcs |>
  select(
    ingredient_name,
    product_rxcui,
    name,
    tty,
    route,
    dose_form,
    ndc11,
    ndc_status
  )

## ----summarize-products-------------------------------------------------------
bb_oral_products |>
  count(ingredient_name, sort = TRUE, name = "n_product_rxcuis")

## ----summarize-ndcs-----------------------------------------------------------
bb_oral_ndcs |>
  count(ingredient_name, sort = TRUE, name = "n_active_ndcs")

## ----summarize-combinations---------------------------------------------------
bb_oral_products |>
  filter(n_ingredients > 1) |>
  select(
    ingredient_name,
    product_rxcui,
    name,
    tty,
    n_ingredients,
    route,
    dose_form
  )

## ----alt-search-rxcui---------------------------------------------------------
if (run_live) {
  bb_oral_rxcuis <- search_drug(
    beta_blocker_names,
    return = "rxcui",
    route = "ORAL",
    include_combos = TRUE,
    concept_status = "active"
  )
} else {
  bb_oral_rxcuis <- read_rxref_example("bb_oral_rxcuis_search.rds")
}

bb_oral_rxcuis

## ----alt-search-ndc-----------------------------------------------------------
if (run_live) {
  bb_oral_ndcs_search_raw <- search_drug(
    beta_blocker_names,
    return = "ndc",
    route = "ORAL",
    ndc_status = "ACTIVE",
    include_combos = TRUE,
    concept_status = "active"
  )

  bb_oral_ndcs_search <- bb_oral_ndcs_search_raw

  if (!"ingredient_name" %in% names(bb_oral_ndcs_search)) {
    bb_oral_ndcs_search <- bb_oral_ndcs_search |>
      left_join(
        bb_ingredients |>
          select(ingredient_rxcui, ingredient_name),
        by = "ingredient_rxcui"
      )
  }

  product_cols <- c(
    "name",
    "tty",
    "route",
    "dose_form",
    "dose_form_group"
  )

  missing_product_cols <- setdiff(product_cols, names(bb_oral_ndcs_search))

  if (length(missing_product_cols) > 0) {
    bb_oral_ndcs_search <- bb_oral_ndcs_search |>
      left_join(
        bb_oral_products |>
          select(
            ingredient_rxcui,
            product_rxcui,
            all_of(missing_product_cols)
          ),
        by = c("ingredient_rxcui", "product_rxcui")
      )
  }

  bb_oral_ndcs_search <- bb_oral_ndcs_search |>
    distinct()
} else {
  bb_oral_ndcs_search <- read_rxref_example("bb_oral_ndcs_search.rds")
}

bb_oral_ndcs_search

## ----products-and-ndcs--------------------------------------------------------
if (run_live) {
  bb_oral_both <- search_drug(
    beta_blocker_names,
    return = "both",
    route = "ORAL",
    ndc_status = "ACTIVE",
    include_combos = TRUE,
    concept_status = "active"
  )
} else {
  bb_oral_both <- read_rxref_example("bb_oral_both_search.rds")
}

names(bb_oral_both)

## ----products-and-ndcs-products-----------------------------------------------
bb_oral_both$products

## ----products-and-ndcs-ndcs---------------------------------------------------
bb_oral_both$ndcs

## ----qc-nonoral-names---------------------------------------------------------
bb_oral_products |>
  filter(grepl(
    "Injection|Injectable|Ophthalmic|Topical|Transdermal|Nasal|Inhalation",
    name,
    ignore.case = TRUE
  ))

## ----qc-routes----------------------------------------------------------------
bb_oral_products |>
  count(route, dose_form_group, sort = TRUE)

## ----qc-combinations----------------------------------------------------------
bb_oral_products |>
  filter(n_ingredients > 1) |>
  count(ingredient_name, sort = TRUE)

## ----qc-without-ndcs----------------------------------------------------------
bb_oral_products |>
  anti_join(
    bb_oral_ndcs |>
      distinct(product_rxcui),
    by = "product_rxcui"
  ) |>
  select(
    ingredient_name,
    product_rxcui,
    name,
    tty,
    route,
    dose_form
  )

