R/parse_rules.R

Defines functions parse_rules

Documented in parse_rules

#' Parse Tier Scoring Rules
#'
#' Converts text-based scoring rules into a named numeric vector.
#'
#' @param text Character string containing one scoring rule per line.
#'
#' @return A named numeric vector containing scoring rules.
#'
#' @examples
#' rules <- parse_rules("
#' 11 = 4
#' 10 = 3
#' 01 = 2
#' 00 = 1
#' ")
#'
#' rules
#'
#' @importFrom stats setNames
#' @export
parse_rules <- function(text) {

  lines <- strsplit(text, "\n")[[1]]

  lines <- trimws(lines)
  lines <- lines[nzchar(lines)]

  if (length(lines) == 0) {
    stop("Aturan penskoran tidak boleh kosong.")
  }

  parsed <- lapply(lines, function(line) {

    parts <- strsplit(line, "=", fixed = TRUE)[[1]]

    if (length(parts) != 2) {
      stop("Format aturan salah: ", line)
    }

    pattern <- trimws(parts[1])

    score <- suppressWarnings(
      as.numeric(trimws(parts[2]))
    )

    pattern <- gsub("[^01]", "", pattern)

    if (!nzchar(pattern)) {
      stop("Pola respons tidak valid: ", line)
    }

    if (is.na(score)) {
      stop("Skor bukan angka: ", line)
    }

    list(
      pattern = pattern,
      score = score
    )
  })

  setNames(
    vapply(parsed, `[[`, numeric(1), "score"),
    vapply(parsed, `[[`, character(1), "pattern")
  )
}

Try the ConverTier2 package in your browser

Any scripts or data that you put into this service are public.

ConverTier2 documentation built on Nov. 12, 2026, 1:07 a.m.