R/helpers_gee.R

Defines functions prepare_gee_data add_parcela_id

add_parcela_id <- function(data, factors = "trat") {
  data <- normalize_factors(data, factors = factors)

  if ("unit" %in% names(data)) {
    if (anyNA(data$unit)) {
      stop("The column 'unit' contains missing values.",
           call. = FALSE)
    }

    # Each explicit experimental unit must belong to only one
    # combination of treatment-factor levels.
    factor_key <- interaction(
      data[factors],
      drop = TRUE,
      lex.order = TRUE
    )

    n_comb_by_unit <- tapply(
      as.character(factor_key),
      as.character(data$unit),
      function(x) length(unique(x[!is.na(x)]))
    )

    bad_units <- names(n_comb_by_unit)[n_comb_by_unit > 1L]

    if (length(bad_units) > 0L) {
      stop(
        "Each experimental unit must belong to only one combination ",
        "of treatment-factor levels. The following unit(s) occur in ",
        "more than one combination: ",
        paste(bad_units, collapse = ", "),
        ". Check the 'unit' identifiers.",
        call. = FALSE
      )
    }

    data$.unit_id <- factor(as.character(data$unit))

  } else {
    if (!"block" %in% names(data)) {
      stop(
        "The experimental unit could not be identified. ",
        "Provide a 'unit' column identifying each experimental unit, ",
        "or provide 'block' so that the unit can be derived from ",
        "block x treatment-factor combination.",
        call. = FALSE
      )
    }

    data$.unit_id <- interaction(
      data[c("block", factors)],
      drop = TRUE,
      lex.order = TRUE
    )
  }

  data$.parcela_id <- data$.unit_id
  data
}

prepare_gee_data <- function(data, factors = "trat") {

  data <- add_parcela_id(data, factors = factors)

  if (!"time" %in% names(data)) {
    stop(
      "The column 'time' is required to prepare longitudinal data.",
      call. = FALSE
    )
  }

  data <- data[
    order(data$.unit_id, data$time),
    ,
    drop = FALSE
  ]

  rownames(data) <- NULL

  data
}

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.