R/count_correct.R

Defines functions count_correct

Documented in count_correct

#' Count the correct answers
#'
#' This function will count the correct responses.
#'
#' @param data Raw data of class \code{data.frame}.
#' @param ... Other input argument for future expansion.
#' @return The raw score calculated of \code{double} type.
#' @importFrom magrittr %>%
#' @importFrom rlang .data
#' @export
count_correct <- function(data, ...) {
  delim <- "-"
  vars_correct <- c("Correctness", "AccLoc", "ACC")
  idx_var_correct <- utils::hasName(data, vars_correct)
  if (any(idx_var_correct)) {
    correctness <- dplyr::pull(data, vars_correct[idx_var_correct])
  } else {
    # no correctness in the original data, requiring other variables
    vars_required <- c("STIM", "Resp")
    if (!all(utils::hasName(data, vars_required))) {
      warning("Cannot determine the correctness from data.")
      return(NA_real_)
    }
    correctness <- data %>%
      dplyr::mutate(
        STIM = strsplit(.data$STIM, delim),
        Resp = strsplit(.data$Resp, delim),
        Correctness = purrr::map2_chr(
          .data$STIM, .data$Resp,
          ~ {
            len_stim <- length(.x)
            len_resp <- length(.y)
            acc <- numeric(len_stim)
            for (i_stim in 1:len_stim) {
              if (i_stim > len_resp) {
                next
              }
              acc[i_stim] <- .x[i_stim] == .y[i_stim]
            }
            paste(acc, collapse = delim)
          }
        )
      ) %>%
      dplyr::pull("Correctness")
  }
  if (!is.numeric(correctness)) {
    correctness <- correctness %>%
      purrr::map(
        ~ strsplit(.x, delim) %>%
          unlist() %>%
          as.numeric()
      ) %>%
      unlist()
  }
  sum(correctness == 1)
}
psychelzh/dataprocr documentation built on Oct. 12, 2019, 1:50 a.m.