R/econn_rbindr.R

#' @title clean_econn
#'
#' @description Function to filter out NA concentration results, body fluids,
#' clean date format, remove extra column, edit column names.
#'
#' @param df Dataframe containing econn data.
#'
#' @return Returns cleaned dataframe.
clean_econn <- function(df) {
  df %<>%
    srms::df_checker() %>%
    dplyr::filter(
      !is.na(F.Concentration),
      Body.Fluid %in% 5:6
    ) %>%
    dplyr::mutate(
      Time.Metering = as.POSIXct(Time.Metering,
                                 format = '%m/%d/%Y %I:%M:%S %p')
    )

  if ('X' %in% names(df)) {
    df %<>%
      dplyr::select(
        -X
      )
  }

  names(df) <- gsub('\\.', ' ', names(df))
  return(df)
}

#' @title econn_rbindr
#'
#' @description Function to read all .txt files of econn data and clean and
#' writes to a CSV file. Must be run with working directory set to the one that
#' contains all of the .txt files.
#'
#' @param assay_name Name of assay contained in data
#'
#' @return Writes rbinded dataframe to CSV file.
#'
#' @export
econn_rbindr <- function(assay_name) {
  files <- list.files('.' , pattern = '*.txt')
  dfs <- lapply(files,
                read.delim, sep = '\t', quote = "", stringsAsFactors = FALSE)

  df <- lapply(dfs, clean_econn) %>% do.call('rbind', .)

  filename <- paste0(assay_name,
                     '_results_',
                     strftime(Sys.time(), format = '%m%d%Y'),
                     '.csv')

  write.csv(df, filename, row.names = FALSE)
}
kimjam/srms documentation built on May 20, 2019, 10:21 p.m.