R/helpers_io_long.R

Defines functions make_long_from_workbook add_design_columns resolve_factor_columns find_wide_cols pick_col parse_num norm_txt

Documented in make_long_from_workbook resolve_factor_columns

#' @keywords internal
norm_txt <- function(x) {
  x <- trimws(as.character(x))
  x <- stringi::stri_trans_general(x, "Latin-ASCII")
  stringi::stri_trans_tolower(x, locale = "en")
}

parse_num <- function(x) {
  if (is.factor(x)) x <- as.character(x)
  suppressWarnings(readr::parse_number(x))
}

#' @keywords internal
pick_col <- function(df, candidates) {

  nm <- names(df)
  nmn <- norm_txt(nm)
  candn <- norm_txt(candidates)

  hit <- which(nmn %in% candn)

  if (length(hit) == 0L) {
    return(NA_character_)
  }

  if (length(hit) > 1L) {
    stop(
      "More than one column matches the same expected role: ",
      paste(nm[hit], collapse = ", "),
      ". Keep only one unambiguous column.",
      call. = FALSE
    )
  }

  nm[hit]
}

find_wide_cols <- function(nms) {
  nmn <- norm_txt(nms)
  keep <- grepl("^f[_ ]*\\d+$", nmn)
  nms[keep]
}


#' Resolve treatment-factor columns
#'
#' Identifies columns corresponding to the factors requested in `factors`.
#'
#' @param df Input data frame whose columns are inspected.
#' @param factors Character vector of treatment-factor names.
#' @return Named character vector mapping requested factors to columns.
#' @keywords internal
resolve_factor_columns <- function(df, factors = "trat") {

  factors <- unique(as.character(factors))

  if (length(factors) == 0L) {
    stop(
      "The factors argument must contain at least one factor.",
      call. = FALSE
    )
  }

  nm <- names(df)
  nmn <- norm_txt(nm)

  out <- stats::setNames(
    rep(NA_character_, length(factors)),
    factors
  )

  for (f in factors) {

    fn <- norm_txt(f)

    candidates <- switch(
      fn,
      "trat" = c("trat", "tratamento", "treatment", "trt"),
      "cultivar" = c("cultivar", "variedade", "variety"),
      "produto" = c("produto", "product"),
      fn
    )

    candidates <- norm_txt(candidates)
    hit <- which(nmn %in% candidates)

    if (length(hit) == 0L) {
      stop(
        "Requested factor not found: ",
        f,
        ". Available columns: ",
        paste(nm, collapse = ", "),
        call. = FALSE
      )
    }

    if (length(hit) > 1L) {
      stop(
        "More than one column matches factor ",
        f,
        ": ",
        paste(nm[hit], collapse = ", "),
        ". Keep only one unambiguous column.",
        call. = FALSE
      )
    }

    out[[f]] <- nm[hit]
  }

  out
}

add_design_columns <- function(df, df0, nm_block, nm_unit) {

  if (!is.na(nm_block)) {
    df$block <- factor(
      trimws(as.character(df0[[nm_block]]))
    )
  }

  if (!is.na(nm_unit)) {
    df$unit <- factor(
      trimws(as.character(df0[[nm_unit]]))
    )
  }

  df
}



#' Detect and convert long- or wide-format workbooks
#'
#' Reads an XLSX workbook, identifies a worksheet in long or wide format,
#' and converts wide-format data to long format when needed.
#'
#' @param path Path to the `.xlsx` workbook.
#' @param sheet_prefer Preferred worksheet, or `NULL` for automatic detection.
#' @param factors Character vector of treatment-factor names.
#' @return Long-format data frame with `source_sheet`, `format`, and
#'   `treatment_factors` attributes.
#' @keywords internal
make_long_from_workbook <- function(path, sheet_prefer = NULL, factors = "trat") {
  sheets <- readxl::excel_sheets(path)
  if (!is.null(sheet_prefer) && sheet_prefer %in% sheets) {
    sheets <- c(sheet_prefer, setdiff(sheets, sheet_prefer))
  }
  tried <- list()

  for (sh in sheets) {
    df0 <- suppressMessages(readxl::read_excel(path, sheet = sh))
    if (nrow(df0) == 0) { tried[[sh]] <- "Empty worksheet"; next }
    names(df0) <- norm_txt(names(df0))

    nm_block <- pick_col(df0, c("block", "bloco"))
    nm_unit  <- pick_col(df0, c("unit", "unidade", "parcela"))
    nm_time  <- pick_col(df0, c("time","tempo","avaliacao","avaliacao","dia","dias","t"))
    nm_class <- pick_col(df0, c("class","classe","escore","esc","nota","severity_class"))
    nm_freq  <- pick_col(df0, c("freq","frequencia","frequencia","n","count","qtde"))
    wide_cols <- find_wide_cols(names(df0))

    factor_cols <- try(
      resolve_factor_columns(df0, factors = factors),
      silent = TRUE
    )
    factors_ok <- !inherits(factor_cols, "try-error")

    # LONG
    if (!is.na(nm_class) && !is.na(nm_freq) && factors_ok &&
        (!is.na(nm_block) || !is.na(nm_unit))) {

      has_time <- !is.na(nm_time) && nm_time %in% names(df0)

      df <- data.frame(
        time = if (has_time) {
          suppressWarnings(as.numeric(df0[[nm_time]]))
        } else {
          NA_real_
        },
        class = factor(df0[[nm_class]]),
        freq = as.numeric(df0[[nm_freq]]),
        check.names = FALSE
      )

      for (factor_name in factors) {
        source_name <- unname(factor_cols[[factor_name]])
        df[[factor_name]] <- factor(
          norm_txt(as.character(df0[[source_name]]))
        )
      }

      df <- add_design_columns(df, df0, nm_block, nm_unit)

      if (all(is.na(df$time)) && has_time) {
        df$time <- parse_num(df0[[nm_time]])
      }

      factor_levels_ok <- all(
        vapply(
          factors,
          function(nm) nlevels(df[[nm]]) >= 1L,
          logical(1)
        )
      )

      if (!all(is.na(df$time)) && factor_levels_ok) {
        attr(df, "source_sheet") <- sh
        attr(df, "format") <- "LONG"
        attr(df, "treatment_factors") <- factors
        return(df)
      } else {
        tried[[sh]] <- "Invalid LONG data (missing time or treatment factor without levels)"
      }
    }

    # WIDE
    if (length(wide_cols) >= 2 && factors_ok &&
        (!is.na(nm_block) || !is.na(nm_unit))) {

      dfw <- df0

      for (factor_name in factors) {
        source_name <- unname(factor_cols[[factor_name]])
        dfw[[factor_name]] <- factor(
          norm_txt(as.character(df0[[source_name]]))
        )
      }

      dfw <- add_design_columns(dfw, df0, nm_block, nm_unit)

      if (!is.na(nm_unit)) {
        # Unidade experimental explicita tem prioridade.
        dfw$.unit_id <- factor(as.character(dfw$unit))
      } else {
        # Sem unit explicita, a unidade e block x combinacao de fatores.
        unit_parts <- c(list(dfw$block), unname(dfw[factors]))
        dfw$.unit_id <- do.call(
          interaction,
          c(unit_parts, list(drop = TRUE, lex.order = TRUE))
        )
      }

      dfw <- dfw |>
        dplyr::group_by(.unit_id) |>
        dplyr::mutate(time = dplyr::row_number()) |>
        dplyr::ungroup()

      dfl <- dfw |>
        tidyr::pivot_longer(
          tidyselect::all_of(wide_cols),
          names_to = "class",
          values_to = "freq"
        ) |>
        dplyr::mutate(
          time = as.numeric(time),
          class = factor(class),
          freq = as.numeric(freq)
        ) |>
        dplyr::select(
          tidyselect::any_of(c("block", "unit")),
          tidyselect::all_of(factors),
          time, class, freq
        )

      factor_levels_ok <- all(
        vapply(
          factors,
          function(nm) nlevels(dfl[[nm]]) >= 1L,
          logical(1)
        )
      )

      if (factor_levels_ok && length(unique(dfl$time)) >= 2) {
        attr(dfl, "source_sheet") <- sh
        attr(dfl, "format") <- "WIDE\u2192LONG"
        attr(dfl, "treatment_factors") <- factors
        return(dfl)
      } else {
        tried[[sh]] <- "Invalid WIDE data"
      }
    }

    if (is.null(tried[[sh]])) {
      if (!factors_ok) {
        tried[[sh]] <- paste0(
          "Requested factor(s) not found: ",
          paste(factors, collapse = ", ")
        )
      } else {
        tried[[sh]] <- "No recognized data format"
      }
    }
  }

  stop(
    "Could not construct LONG data from any worksheet.\n",
    paste(sprintf("- %s: %s", names(tried), unlist(tried)), collapse = "\n")
  )
}

Try the infectionIndex package in your browser

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

infectionIndex documentation built on Dec. 4, 2026, 5:10 p.m.