R/utils.R

Defines functions vars expand_cols quo2char lu

Documented in vars

# various utility functions (not to be exported by package)

# length of unique elements -----------------------------------------------
# number of unique non NA elements

lu <- function(x) length(unique(x[!is.na(x)]))

# testing
if (FALSE) {
    x <- c(1, 1, 2, 3, NA, NA)
    lu(x)
}



# quo2char ------------------------------------------------------

quo2char <- function(.vars) {
    # args:
    #   .vars-- a quosture e.g. made by vars()
    # returns:
    #   character vector
    check_quosures(.vars)

    out <- stringr::str_replace(as.character(.vars), "^~", "")
    out
}



# expand column combinations ----------------------------------------------

expand_cols <- function(df, cols = c("date", "InstrumentVersion")) {
    # args:
    #     df--a dataframe that includes a date column
    #     cols -- character vector of names of columns in df, must include date
    # returns:
    #     every combination of the cols, (along whole range of date, if a date
    #     column is provided)

    check_cols(df, cols)

    cols <- unique(cols)

    names(cols) <- cols
    col_vecs <- purrr::map(cols, function(x) unique(df[[x]][!is.na(df[[x]])]))

    # want to create vector of dates
    if ("date" %in% cols) {
        col_vecs[["date"]] <- seq(min(col_vecs[["date"]]),
                                  to = max(col_vecs[["date"]]),
                                  by = "1 day")
    }

    out <- expand.grid(col_vecs, stringsAsFactors = FALSE)
    as_tibble(out)
}

#'  Select variables
#'
#'  This is the vars function from dplyr package see \code{?dplyr::vars}
#'
#' @param ... variables to include
#' @export
vars <- function(...){
    dplyr::vars(...)
}
MartinHoldrege/turnr documentation built on May 16, 2020, 10:39 a.m.