R/add_clre_tech.R

#' @title add_clre_tech
#'
#' @description Function to add Technology field to CL Reagent complaints.
#'
#' @param df Dataframe of CL Reagent complaints
#' @param filename Name of .csv file to write to. Defaults to 'clre_withtech.csv'
#' @param write If TRUE, writes dataframe to filename. Defaults to TRUE.
#'
#' @return Returns dataframe with Technology field added.
#' @export

add_clre_tech <- function(
  df,
  filename = 'clre_withtech.csv',
  write = TRUE
) {

  df <- df_checker(df)
  # look for column name that contains call subject
  cs_name <- names(df)[grepl('*callsubject|*call_subject|*call.subject',
                             tolower(names(df)))][1]
  # look for column name that contains analyzer
  analyzer <- names(df)[grepl('*family_code|*analyzer|*family.code',
                              tolower(names(df)))][1]

  # remove rows that have a call subject in exception list
  df <- df[!(df[, cs_name] %in% exceptions$Str_callsubject), ]

  # assign appropriate technology for CALBRTR, CKMB, QCMAT
  temp1 <- df %>%
    dplyr::filter_(
      paste0(cs_name, " %in% c('CALBRTR', 'CKMB', 'QCMAT')")
    ) %>%
    dplyr::mutate(Technology = NA)

  if (nrow(temp1) > 0) {
    temp1$Technology[temp1[, cs_name] == 'CALBRTR' & temp1[, analyzer] %in% c(
      'FS 4600 SYS', '250', 'FS', '5600'
    )] <- 'MicroSlide'

    temp1$Technology[temp1[, cs_name] == 'CALBRTR' & temp1[, analyzer] %in% c(
      'ECI', '3600'
    )] <- 'MicroWell'

    temp1$Technology[temp1[, cs_name] == 'CKMB' & temp1[, analyzer] %in% c(
      'FS 4600 SYS', '250', 'FS'
    )] <- 'MicroSlide'

    temp1$Technology[temp1[, cs_name] == 'CKMB' & temp1[, analyzer] %in% c(
      'ECI', '3600', '5600'
    )] <- 'MicroWell'

    temp1$Technology[temp1[, cs_name] == 'QCMAT' & temp1[, analyzer] %in% c(
      'FS 4600 SYS', '250', 'FS', '5600'
    )] <- 'MicroSlide'

    temp1$Technology[temp1[, cs_name] == 'QCMAT' & temp1[, analyzer] %in% c(
      'ECI', '3600'
    )] <- 'MicroWell'
  }

  # use simple join to assing rest of complaints' technology
  # any missing technology field is MicroSlide
  temp2 <- df %>%
    dplyr::filter_(
      paste0('!(', cs_name, " %in% c('CALBRTR', 'CKMB', 'QCMAT'))")
    ) %>%
    dplyr::mutate(Technology = NA)

  if (nrow(temp2) > 0) {
    for (cs in unique(temp2[, cs_name])) {
      if (cs %in% unique(technologies$str_callsubject)) {
        temp2$Technology[temp2[, cs_name] == cs] <- technologies$Technology[
          technologies$str_callsubject == cs
          ]
      }
    }

    temp2$Technology[is.na(temp2$Technology)] <- 'MicroSlide'

  }
  data <- rbind(temp2, temp1)

  # will write to whatever is the current working directory
  if (write) {
    write.csv(x = data, file = filename, row.names = FALSE)
  }

  return(data)
}
kimjam/srms documentation built on May 20, 2019, 10:21 p.m.