R/get_variable.R

Defines functions get_variable

Documented in get_variable

#' get_variable()
#'
#' Get the code and label metadata for a single variable from the Census Bureau
#'
#' @description Function produces a dataframe of a variable's ID and its
#'    label from the Census Bureau's publicly available
#'    \href{https://www.census.gov/data/developers/data-sets.html}{datasets}.
#' @param dataset A string that sets the name of the dataset of interest (e.g. "acs/acs5").
#'   See \code{Rcensus::get_dataset_names()} for available dataset names.
#' @param vintage An optional numeric or vector of numerics that sets the year(s) of interest.
#' @param variable_name A string that sets the name of the variable of interest
#' @param brief If TRUE out of the total columns, will return only columns `name`, `label`, `predicateType`.
#'
#' @import data.table httr jsonlite
#'
#' @return A data.table
#'
#' @author Rick Dean
#'
#' @export
get_variable <- function(
  dataset,
  vintage = NULL,
  variable_name,
  brief = FALSE){

  # Create a string url based on the submitted parameters
  a_url <- .get_url(dataset, vintage)

  a_url <- paste0(a_url, "/variables/", variable_name, ".json")

  # Make a web request
  resp <- httr::GET(a_url)

  # Check the response as valid JSON
  .check_response(resp)

  # Parse the response and return raw JSON
  raw_json <- .parse_response(resp)

  var_dt <- data.table::setDT(raw_json)

  if(brief){
    return(var_dt[, .(name, label, predicateType)])
  }else {
    return(var_dt)
  }
}
deandevl/Rcensus documentation built on Aug. 9, 2022, 8:24 p.m.