R/get_gender.R

Defines functions get_gender

Documented in get_gender

#' Determine the gender of a first name
#'
#' @param name The first name you want the gender for (can also take a vector of names - max 10)
#' @param country_id The ISO 3166-1 alpha-2 code for the country (see gendeR::df_iso for ISO 3166-1 alpha-2 codes)
#' @param simple_response If TRUE, you only get the gender. If FALSE, you also get the probability of correct gender and a count of names in Genderize.io's database
#'
#' @return A dataframe if simple_response = FALSE, a character if simple_response = TRUE
#'
#' @examples get_gender(name = "Sebastian", country_id = "DK", simple_response = TRUE)
#' @export
get_gender <- function(name = "Sebastian", apikey = NULL, country_id = NULL, simple_response = FALSE) {

    url <- "https://api.genderize.io/"

    # Build query: names
    query <- as.list(name)
    names(query) <- rep("name[]", length(name))

    # Build query: country_id
    if (!is.null(country_id)) query <- c(query, country_id = country_id)

    # Build query: apikey
    if (!is.null(apikey)) query <- c(query, apikey = apikey)

    # Get response
    resp <- httr::GET(url = url, query = query)

    # Check status code
    switch(
        EXPR = which(c(200, 400, 429, 500) %in% httr::status_code(resp)),
        parsed <- httr::content(resp),
        stop("Bad Request"),
        stop("Too Many Requests"),
        stop("Internal Server Error")
    )

    # Parse
    if (exists("parsed")) {

        result <- lapply(parsed, function(entry) {

            data.frame(
                name = ifelse(is.null(entry$name), NA, entry$name),
                gender = ifelse(is.null(entry$gender), NA, entry$gender),
                prob = ifelse(is.null(entry$prob), NA, entry$prob),
                count = ifelse(is.null(entry$count), NA, entry$count),
                stringsAsFactors = FALSE
            )

        })

        result <- do.call(rbind, result)

    } else {

        result <- data.frame(
            name = name,
            gender = NA,
            probability = NA,
            count = NA,
            stringsAsFactors = FALSE
        )

    }

    # If simple_reponse = TRUE only return the gender
    if (simple_response) result <- result$gender
    message(resp$headers$`x-rate-limit-remaining`, " calls left.")

    return(result)
}
Steensson/gendeR documentation built on May 7, 2019, 1:23 p.m.