david-y
11/22/2017 - 2:41 PM

some examples of common io tasks

some examples of common io tasks

## for installing needed packages
list.of.packages <- c("readr", "RODBC", "reshape2", "ggplot2", "lubridate",
                      "plyr", "scales", "sde", "outliers", "gridExtra")
new.packages <- list.of.packages[!(list.of.packages %in% 
                                     installed.packages()[,"Package"])]
if(length(new.packages)) install.packages(new.packages)

## for cleaning the environment of objects
rm(list=ls())
gc()

## for turning warnings on and off (esp useful when knitting)
options(warn = -1)
options(warn = 0)  # don't forget to turn it back on

## for recording execution time
# place at beginning
time.st <- strptime(date(), format="%a %b %d %H:%M:%S %Y")
# place at end
time.end <- strptime(date(), format="%a %b %d %H:%M:%S %Y")
print(paste("Run Time:", difftime(time.end, time.st, tz="EST", units="mins"), 
            "mins", sep=" "))
            
## for obtaining user input to be utilized later
input_str_pwr <- readline(
  paste(
    'Do you want to run pwr parameterization?', 
    '1 for yes; 0 for no', 
    ']>',
    sep=''
  )
)

## for creating a log file
temp_folder <- "P:\\Risk\\Risk - Risk Management\\aa_Yang\\Development\\Temp R Output\\"
working_dir <- getwd()
setwd(temp_folder)
log_file <- paste("GMaR", format(as.Date(report_date), "%m-%d-%y"), 
                  format(Sys.time(), "%m-%d-%y_%H-%M-%S"), "log.txt", sep = "_")
sink(log_file, type = "output", split = TRUE) # place at start

sink() # place at end
setwd(working_dir)

## for reading csv files using readr::read_csv
holiday.def <- read_csv(paste(source_directory, "Holiday_Def.csv", sep = ""), 
                        col_names = c("Date", "Holiday"),
                        col_types = list(
                        Date = col_date(format="%m/%d/%Y"),
                        Holiday = col_logical()), 
                        skip = 1)

## for creating folder directory (one level at a time)
file_path_out_folder <- paste("P:\\Risk\\Risk-Operations\\Budget Runs\\", 
                          year(begin_date - 1), "\\", month(begin_date-1, label = TRUE, abbr = TRUE),
                          "\\Archive\\", sep = "")
dir.create(file_path_out_folder)