R/utils.R

Defines functions postgres_present write_to_postgres_tester int_breaks_rounded

Documented in int_breaks_rounded postgres_present write_to_postgres_tester

#' Postgres connection test
#'
#' function to test whether testing PostgreSQL db container up
#'

postgres_present <- function() {

  # capture all docker container names currently running
    docker_containers <- system("docker ps --format '{{.Names}}'", intern = TRUE)

  # check whether testing database is running and output logical
    any(grepl("^post-gres-tester$", docker_containers))
}


#' Upload data to test Postgres db
#'
#' @param upload object or list of objects
#' @importFrom DBI dbConnect dbDisconnect
#' @importFrom RPostgres Postgres

write_to_postgres_tester <- function(upload) {
  # creates a connection to the postgres database
  # note that "con" will be used later in each connection to the database
  con <- DBI::dbConnect(RPostgres::Postgres(),
                        dbname = "postgres",
                        host = "0.0.0.0",
                        port = 5432,
                        user = "postgres",
                        password = "pgtest")


  # WRITE data to db
  purrr::walk2(upload, names(upload),
             .f = ~ DBI::dbWriteTable(con, .y, .x))


  # close connections on exit
  DBI::dbDisconnect(con)

}



#' @title Rount breaks to integers
#'
#' @description To generate axes breaks dynamically in ggplot, 
#' sometimes you need count values rather than a continuous scale. 
#' This function takes a range of integers and generates n equally 
#' spaced integer breaks. 
#' @param x an object coercible to numeric by as.numeric.
#' @param n integer giving the desired number of intervals. 
#' Non-integer values are rounded down.
#'
#' @return numeric equally spaced vector
#'

int_breaks_rounded <- function(x, n = 5)  {
  
  pretty(x, n)[round(pretty(x, n),1) %% 1 == 0]
  
}
  
JayAchar/hisreportr documentation built on March 18, 2020, 5:57 a.m.