R/read_data.R

Defines functions read_db_QCM

Documented in read_db_QCM

#' read excel file to create questions
#'
#' @param file character, file adress
#'
#' @return question database
#' @export
read_db_QCM <- function(file) {

  db <- rio::import(file = file, setclass = 'data.table') %>% data.table::setDT(.)
  name_verification <- names(db)
  if (any(!grepl('^question|^y|^n|^tag', tolower(name_verification)))) {
    stop('error: the columns must start with \'question\', \'y\', \'n\' and \'tag\' (in that order)')
  }
  if (!grepl('^question', tolower(name_verification[1]))) {
    stop('error: the first column must be named \'question\' and contain the questions')
  }
  if (any(!grepl('^y|^n', tolower(name_verification[-c(1,length(name_verification))])))) {
    stop('error: the answer columns must start with a \'y\' for correct answers and \'n\' for wrong answers')
  }
  if (!grepl('^tag', tolower(name_verification[length(name_verification)]))) {
    stop('error: the tag columns must be named \'tag\' and contain the tags')
  }

  questions <- name_verification[1]
  correct <- name_verification[grepl('^y', tolower(name_verification))]
  wrong <- name_verification[grepl('^n', tolower(name_verification))]
  tag <- name_verification[grepl('^tag', tolower(name_verification))]

  QCM_db <- purrr::transpose(db)

  purrr::map(QCM_db,~list(question = .x[[questions]],
                          correct = .x[correct] %>% .[purrr::map_lgl(.,function(.y) !is.na(.y))] %>% purrr::map_chr(as.character) %>% purrr::set_names(NULL),
                          wrong = .x[wrong] %>% .[purrr::map_lgl(.,function(.y) !is.na(.y))] %>% purrr::map_chr(as.character) %>% purrr::set_names(NULL),
                          tag = .x[[tag]]))

}
Guillaume-Lombardo/rQCM documentation built on Oct. 30, 2019, 6:37 p.m.