Skip to content

Instantly share code, notes, and snippets.

@stephenrho
Last active July 16, 2024 18:27
Show Gist options
  • Save stephenrho/66cf370cf7cb2248f39fed7e266ce027 to your computer and use it in GitHub Desktop.
Save stephenrho/66cf370cf7cb2248f39fed7e266ce027 to your computer and use it in GitHub Desktop.
Get NDC and RxCui from openFDA via generic drug name
query_fda <- function(dname, route){
dname <- gsub(" ", "%", dname)
dname <- sprintf('"%s"', dname) # enclose in quotes
if (!missing(route) & !is.null(route)){
dname <- sprintf('%s+AND+route:"%s"', dname, route)
}
url <- sprintf('https://api.fda.gov/drug/ndc.json?search=generic_name:%s&limit=100', dname)
res <- httr::GET(url)$content |>
rawToChar() |>
jsonlite::fromJSON()
if ("error" %in% names(res) | !"results" %in% names(res)){
NULL
} else{
res$results
}
}
get_fda <- function(druglist, route=NULL){
lapply(druglist, \(x) lapply(x, query_fda, route=route))
}
get_ndc <- function(fda){
lapply(fda, \(x) sapply(x, \(xx){
if ("packaging" %in% names(xx)){
sapply(xx$packaging, \(xxx) xxx$package_ndc) |>
unlist() |>
unique()
} else{
NULL
}
})
)
}
get_rxcui <- function(fda){
lapply(fda, \(x) sapply(x, \(xx){
if ("openfda" %in% names(xx)){
xx$openfda$rxcui |>
unlist() |>
unique()
} else {
NULL
}
})
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment