R/utilities.R

Defines functions estimable_labels estimable_num estimable_cell estimable_table sas_glm sas_e2 sas_contains glm_model_matrix sas_col_order matrix_table get_singular get_zeta force_width fit_width get_line_count get_text_width fmt_col rename_data drop_data keep_data get_table_vector subset_data resolve_arg clear_factors get_valid_obs get_vars get_obs get_formulas fix_var_names add_paired_vars get_ttest_type copy_df_attributes copy_attributes_sp perform_set get_class_names restore_datatypes get_maxdec get_alpha fill_missing log_output log_logr has_report has_view has_output get_name get_option has_option option_true has_report filenm show_viewer flatten_list output_report

# Report Utilities ------------------------------------------------------



#' @import reporter
#' @noRd
output_report <- function(lst,
                          dir_name, file_name, out_type = 'HTML',
                          style = NULL,
                          titles = NULL, margins = 1,
                          viewer = FALSE,
                          pages = 1) {


  if (is.null(dir_name)) {
    stop("Path cannot be null")

  } else {


    targetDir <- dir_name

    if (dir.exists(targetDir) == FALSE)
      dir.create(targetDir)

    flnm <- file_name
  }

  rpt <- create_report(font = 'Arial', orientation = 'portrait', missing = "",
                       font_size = 8)
  rpt <- set_margins(rpt, top = margins, bottom = margins,
                     left = margins, right = margins)



  if (!is.null(style)) {

    if (any(class(style) %in% "style_spec")) {

      rpt <- add_style(rpt, style = style)

    } else if (all(class(style) %in% "character")) {


      rpt <- add_style(rpt, theme = style)

    } else {

      stop("Report style parameter value is invalid.")
    }

  } else {

    thm <- get_theme("SASDefault")
    thm$font_size <- 8
    thm$title_font_size <- 10

    rpt <- add_style(rpt, style = thm)

  }

  # If everything thrown on one page, flatten
  # the list to make it easier to deal with different objects.
  if (pages == 1) {

    nlst <- flatten_list(lst)

  } else {

    nlst <- lst

  }


  for (j in seq_len(pages)) {

    if (pages == 1) {
      pg <- nlst

    } else {
      pg <- nlst[[j]]
    }

    # Get page item names
    lnms <- names(pg)

    for (i in seq_len(length(pg))) {

      brk <- FALSE
      if (pages > 1 & i == length(pg))
        brk <- TRUE

      # Assign page data
      dt <- pg[[i]]

      # Get item name
      lnm <- lnms[i]

      if ("data.frame" %in% class(dt)) {
        if (viewer == TRUE) {

          if ("CAT" %in% names(dt)) {
            lbl <-  attr(dt$CAT, "label")
            if (is.null(lbl))
              lbl <- "CAT"
            nms <- names(dt)
            names(dt) <- gsub("CAT", "stub", nms, fixed = TRUE)
          }

          if ("STAT" %in% names(dt)) {
            if ("Chi-Square" %in% dt$STAT) {
              nms <- names(dt)
              names(dt) <- gsub("STAT", "stub", nms, fixed = TRUE)
            }
          }


          if ("stub" %in% names(dt)) {

            lbl <- attr(dt$stub, "label")
            if (is.null(lbl))
              lbl <- ""

          }

          # Create table
          tbl <- create_table(dt, borders = c("all"))

          # Dedupe stub column if it exists
          if ("stub" %in% names(dt)) {

            wdth <- attr(dt$stub, "width")
            if (is.null(wdth)) {
              wth <- rpt$char_width * nchar(lbl)
            } else {
              wth <- rpt$char_width * wdth
            }
            tbl <- define(tbl, "stub", dedupe = TRUE, label =lbl, width = wth,
                          standard_eval = "true")

          }

        } else {

          # Create table
          tbl <- create_table(dt, borders = c("outside"))
        }

        # Add titles
        tt <- NULL
        if (i == 1) {

          if (!is.null(titles))
            tt <- titles

        }

        if (!is.null(attr(dt, "ttls")))
          tt <- c(tt, attr(dt, "ttls"))

        if (!is.null(tt))
          tbl <- titles(tbl, tt)

        #browser()
        # Add spanning headers if requested
        # spns <- attr(dt, "spans")
        # if (!is.null(spns)) {
        #
        #   for (i in seq_len(length(spns))) {
        #     spn <- spns[[i]]
        #     tbl <- spanning_header(tbl, label = spn$label, from = as.character(spn$start),
        #                            to = as.character(spn$end), level = spn$level,
        #                            standard_eval = TRUE)
        #
        #   }
        #
        # }

        # Append table to report
        rpt <- add_content(rpt, tbl, align = 'center', page_break = brk)



      } else if ("ggplot" %in% class(dt)) {

        if (viewer == TRUE) {

          # Create plot content
          fig <- create_plot(dt, height = 3, width = 3.5)

        } else {

          # Create plot content
          fig <- create_plot(dt, height = 4, width = 5)


        }

        # Add plot content
        rpt <- add_content(rpt, fig, align = 'center', page_break = brk)


      } else if ("plot_spec" %in% class(dt)) {

        # Add plot content
        rpt <- add_content(rpt, dt, align = 'center', page_break = brk)

      } else if ("list" %in% class(dt)) {
        if ("plot_spec" %in% class(dt[[1]])) {

          for (pobj in dt) {

            rpt <- add_content(rpt, pobj, align = 'center', page_break = brk)
          }

        }

      } else if ("character" %in% class(dt)) {
        rpt <- add_content(rpt, create_text(dt, align = "center"),
                           align = 'left', page_break = brk)
      }

    } # Tables


  } # Pages


  ret <- c()

  # Deal with multiple output types
  for (ot in out_type) {

    fl <- flnm
    if (all(grepl(".", flnm, fixed = TRUE) == FALSE))
      fl <- paste0(flnm, ".", tolower(ot))

    pth <- file.path(targetDir, fl)


    if (utils::packageVersion("reporter") >= "1.3.6") {

      res <- write_report(rpt, file_path = pth,
                          output_type = ot, log = !viewer)
    } else {
      res <- write_report(rpt, file_path = pth, output_type = ot)

    }

    ret[length(ret) + 1] <- res$modified_path

  }


  return(ret)
}


flatten_list <- function(lst) {

  nlst <- list()
  idx <- c(1)
  lvl <- 1
  obj <- NULL
  while(TRUE) {
    tmp <- lst
    for (i in seq(1, lvl)) {
      if (idx[i] <= length(tmp)) {
        tmp <- tmp[[idx[i]]]
      } else {
        tmp <- NULL
      }
    }
    if (is.null(tmp)) {
      if (lvl == 1) {
        break
      } else {
        lvl <- lvl - 1
        idx <- idx[seq(1, lvl)]
      }
    } else if (all(class(tmp) == "list")) {
      lvl <- lvl + 1
    } else {

      nlst[[length(nlst) + 1]] <- tmp
    }


    if (is.na(idx[lvl])) {
      idx[lvl] <- 1
    } else {
      idx[lvl] <- idx[lvl] + 1
    }
  }


  return(nlst)

}

# There are two test cases for this, but they can't be run with testthat
# as part of a normal command check.  Have to run them interactively
# in dev mode.
#' @noRd
show_viewer <- function(path) {

  pth <- ""

  #print(paste0("path: ", path))

  if (file.exists(path)) {

    opts <- options("procs.print")[[1]]
    if (is.null(opts))
      opts <- TRUE

    if (opts == TRUE) {

      pth <- path

      viewer <- getOption("viewer")

      if (!is.null(viewer))
        viewer(pth)
      else
        utils::browseURL(pth)

    }

  }


  return(pth)

}

#' @noRd
# get_location <- function(proc_type, location) {
#
#   ret <- c(dir_name = "",
#            file_name = "")
#
#   if (is.null(location)) {
#
#     ret["dir_name"] <- tempdir()
#     ret["file_name"] <- proc_type
#
#   } else if (dir.exists(location)) {
#
#     ret["dir_name"] <- location
#     ret["file_name"] <- proc_type
#
#   } else {
#     ret["dir_name"] <- dirname(location)
#     ret["file_name"] <- filenm(location)
#   }
#
#   if (dir.exists(ret["dir_name"] ) == FALSE) {
#     dir.create(ret["dir_name"] )
#
#   }
#
#
#   return(ret)
#
# }


#' @noRd
filenm <- function(path) {

  flnm <- basename(path)

  pos <- strsplit(flnm, ".", fixed = TRUE)
  flnm <- pos[[1]][1]

  return(flnm)

}



has_report <- function(outreq) {

  ret <- FALSE

  if (!is.null(outreq)) {
    for (itm in outreq) {

      if (!is.null(itm$report)) {
        if (itm$report == TRUE)
          ret <- TRUE

      }
    }
  }


  return(ret)

}

# get_report_name <- function(outreq) {
#
#   ret <- ""
#
#   if (!is.null(outreq)) {
#
#     nms <- names(outreq)
#     for (nm in nms) {
#
#       if (!is.null(outreq[[nm]]$report)) {
#         if (outreq[[nm]]$report == TRUE)
#           ret <- nm
#
#       }
#     }
#   }
#
#
#   return(ret)
#
# }


# Option utilities --------------------------------------------------------



#' @noRd
option_true <- function(options, name, default = FALSE) {

  ret <- NULL


  if (!is.null(options)) {
    nms <- names(options)

    # Try to find named option
    if (!is.null(nms)) {

      if (tolower(name) %in% tolower(nms)) {
        # Force names to lower case
        names(options) <- tolower(nms)
        # See if name exists
        vl <- options[[tolower(name)]]
        if (!is.null(vl)) {
          if (vl == TRUE)
            ret <- TRUE
          else
            ret <- FALSE
        }
      }
    }

    # Try to find keyword
    if (is.null(ret)) {

      if (tolower(name) %in% tolower(options)) {

        ret <- TRUE
      }
    }
  }

  # Give up and send default
  if (is.null(ret)) {
    ret <- default
  }

  return(ret)

}

has_option <- function(options, name) {


  ret <- NULL


  if (!is.null(options)) {
    nms <- names(options)

    # Try to find named option
    if (!is.null(nms)) {
      if (tolower(name) %in% tolower(nms)) {
        ret <- TRUE
      }
    }

    # Try to find keyword
    if (is.null(ret)) {

      if (tolower(name) %in% tolower(options)) {

        ret <- TRUE
      }
    }
  }

  if (is.null(ret))
    ret <- FALSE

  return(ret)

}


get_option <- function(options, name, default = NULL, evl = TRUE) {

  ret <- NULL


  if (!is.null(options)) {
    nms <- names(options)

    # Try to find named option
    if (!is.null(nms)) {

      if (tolower(name) %in% tolower(nms)) {

        # Force names to lower case
        names(options) <- tolower(nms)
        # See if name exists
        vl <- options[[tolower(name)]]
        if (evl == FALSE) {
          ret <- gsub('"', "", vl, fixed = TRUE)
        } else if (!is.null(vl)) {
          ret <- tryCatch(eval(str2expression(vl)),
                          error = function(cond){vl})
        }
      }
    }

    # Try to find keyword
    if (is.null(ret)) {

      if (tolower(name) %in% tolower(options)) {

        ret <- TRUE
      }
    }
  }

  # Give up and send default
  if (is.null(ret)) {
    ret <- default
  }


  return(ret)

}

get_name <- function(nm = NULL, var = NULL, bylbl = NULL, addvar = FALSE) {

  vnm <- ""

  if (is.null(nm))
    vnm <- var
  else if (nchar(nm) == 0)
    vnm <- var
  else if (addvar)
    vnm <- paste0(nm, ": ", var)
  else
    vnm <- nm

  if (length(bylbl) == 0) {

    ret <- vnm
  } else {

    ret <- paste0(bylbl, vnm)

  }


  return(ret)
}

has_output <- function(outpt) {

  glb <- options("procs.interactive")[[1]]

  ret <- TRUE

  if (!is.null(glb)) {

    if (glb == TRUE)
      ret <- FALSE
  }

  if (!is.null(outpt)) {
    if (any(tolower(outpt) %in% c("report", "none"))) {
      ret <- FALSE
    }

    if (any(tolower(outpt) %in% c("out"))) {
      ret <- TRUE
    }

  }

  return(ret)
}

has_view <- function(opts) {

  glb <- options("procs.interactive")[[1]]

  ret <- TRUE

  if (!is.null(glb)) {

    if (glb == FALSE)
      ret <- FALSE
  }


  if (!is.null(opts)) {
    if (any(tolower(opts) %in% c("noprint"))) {
      ret <- FALSE
    }

    if (any(tolower(opts) %in% c("print"))) {
      ret <- TRUE
    }

  }

  return(ret)

}

has_report<- function(outpt) {


  ret <- FALSE


  if (!is.null(outpt)) {
    if (any(tolower(outpt) %in% c("report"))) {
      ret <- TRUE
    }

  }

  return(ret)

}

# Logging Utilities ---------------------------------------------------------



# get_by_ds <- function(byvals) {
#
#   ret <- as.data.frame(I(byvals), stringsAsFactors = FALSE)
#   names(ret) <- names(byvals)
#   rownames(ret) <- NULL
#
#   return(ret)
# }


#' @noRd
log_logr <- function(x) {

  if (length(find.package('logr', quiet=TRUE)) > 0) {
    if (utils::packageVersion("logr") >= "1.2.0") {
      logr::log_hook(x)
    }
  }
}


# Check if logr.output option is set or not
log_output <- function() {

  ret <- TRUE
  tmp <- options("logr.output")
  if (!is.null(tmp$logr.output)) {

    ret <- tmp$logr.output

  }

  return(ret)
}


# parse_tables <- function(nms, tstr) {
#
#  vl <- "D * (A--C)"
#
#   rng <- regexec("[a-zA-Z0-9.]+\\-\\-[a-zA-Z0-9.]+", vl)
#
#   rng
#
# }

# Other Utilities ---------------------------------------------------------



fill_missing <- function(ds, num) {

  nas <- rep(NA, num - 1)
  nw <- list()

  for (nm in names(ds)) {

    nw[[nm]] <- nas
  }

  dfn <- as.data.frame(nw, stringsAsFactors = FALSE)

  ret <- rbind(ds, nw)


  return(ret)

}

get_alpha <- function(opts) {

  ret <- .05

  if (!is.null(opts)) {

    nms <- tolower(names(opts))
    if ("alpha" %in% nms) {

      ret <- opts[["alpha"]]

      if (!is.numeric(ret)) {

        ret <- as.numeric(ret)
      }
    }

  }

  return(ret)
}


get_maxdec <- function(opts) {

  ret <- "%.7f"

  if (!is.null(opts)) {

    nms <- tolower(names(opts))
    if ("maxdec" %in% nms) {

      tmp <- opts[["maxdec"]]

      if (!is.numeric(tmp)) {

        tmp <- as.numeric(tmp)
      }

      if (is.numeric(tmp)) {

        ret <- paste0("%.", tmp, "f")
      }
    }

  }

  return(ret)
}



restore_datatypes <- function(res, data, class, clsnms = NULL) {


  if (is.null(clsnms))
    clsnms <- get_class_names(class)

    for (k in seq_len(length(class))) {
      if (nrow(data) == 0) {

        res[[clsnms[k]]] <- NA

      } else {
        if (any(class(data[[class[k]]]) == "factor")) {

          if (any(class(data[[class[k]]]) == "ordered")) {
            res[[clsnms[k]]] <- factor(res[[clsnms[k]]],
                                       levels = attr(data[[class[k]]], "levels"),
                                       ordered = TRUE)
          } else {
            res[[clsnms[k]]] <- factor(res[[clsnms[k]]],
                                       levels = attr(data[[class[k]]], "levels"))
          }

        } else if (all(class(data[[class[k]]]) == "Date")) {

          res[[clsnms[k]]] <- as.Date(res[[clsnms[k]]])

        } else if (typeof(data[[class[k]]]) == "integer") {

          res[[clsnms[k]]] <- as.integer(res[[clsnms[k]]])

        } else if (typeof(data[[class[k]]]) == "numeric") {

          res[[clsnms[k]]] <- as.numeric(res[[clsnms[k]]])
        }
      }

    }


  return(res)
}


get_class_names <- function(class) {


  # Create name lookup
  if (length(class) == 1)
    clsnms <- "CLASS"
  else
    clsnms <- paste0("CLASS", seq(1, length(class)))

  names(clsnms) <- class

  return(clsnms)

}




# Perform the set operation.  Works on main
# dataset plus one or more datasets.
perform_set <- function(dta, stdta) {

  # Save off class
  dtacls <- class(dta)

  # Work with pure data frames.
  # Tibbles will mess with names.
  dta <- as.data.frame(dta)

  # Put in list
  if ("data.frame" %in% class(stdta))
    dtalst <- list(stdta)
  else
    dtalst <- stdta

  # Collect Names
  fnms <- names(dta)

  # Assign counter to ensure stacking
  dta[["..ds"]] <- 0

  ret <- dta

  # Stack datasets
  for (i in seq_len(length(dtalst))){

    tmp <- as.data.frame(dtalst[[i]])
    nnms <- names(tmp)
    fnms <- c(fnms, nnms[!nnms %in% fnms])
    tmp[["..ds"]] <- i
    ret <- merge(ret, tmp, all = TRUE, sort = FALSE)

  }

  # Clean up counter
  ret[["..ds"]] <- NULL
  dta[["..ds"]] <- NULL

  # Rename so first dataset drives naming
  # Can easily break if name has been changed.
  ret <- tryCatch({ret[ , fnms]}, error = function(cond){ret})

  # Restore attributes
  ret <- copy_attributes_sp(dta, ret)
  ret <- copy_df_attributes(dta, ret)

  # Restore original class
  class(ret) <- dtacls

  return(ret)

}

copy_attributes_sp <- function(df1, df2) {

  ret <- df2

  for (nm in names(df2)) {

    col <- df1[[nm]]
    if (!is.null(col)) {
      for (at in names(attributes(col))) {

        if (!at %in% c("levels")) {

          attr(ret[[nm]], at) <- attr(col, at)
        }

      }
    }

  }

  return(ret)
}


# Copies attributes on data frame from one df to another
# Skips rownames and names, which can cause trouble.
copy_df_attributes <- function(src, trgt) {

  atts <- attributes(src)

  ret <- trgt

  for (anm in names(atts)) {

    if (!anm %in% c("names", "row.names")) {
      attr(ret, anm) <- atts[[anm]]
    }
  }

  return(ret)
}


get_ttest_type <- function(txt) {

  ret <- txt
  if (length(grep(":", txt, fixed = TRUE)) > 0) {

    pos <- unlist(gregexpr(':', txt, fixed = TRUE))[1]
    ret <- substring(txt, pos + 1)

  }


  return(ret)

}


# Function to split the paired parameter string and create
# separate variables for VAR1, VAR2, and DIFF
add_paired_vars <- function(dt, vlbl, shape) {

  if (is.null(vlbl)) {

    ret <- dt

  } else {

    if (shape %in% c("wide", "stacked")) {
      nms <- names(dt)
      slbl <- strsplit(vlbl, "-", fixed = TRUE)
      pos <- match("VAR", nms)
      ret <- dt

      ret[["LBL"]] <- as.integer(sub("..diff", "", ret[["VAR"]], fixed = TRUE))
      ret[["DIFF"]] <- ret[["VAR"]]
      for (i in seq_len(nrow(ret))) {
        lbl <- ret[["LBL"]][i]
        ret[["VAR1"]][i] <- trimws(slbl[[lbl]][1])
        ret[["VAR2"]][i] <- trimws(slbl[[lbl]][2])
      }
      ret[["VAR"]] <- NULL
      ret[["LBL"]] <- NULL

      # Rearrange df
      prenms <- c()
      if (pos > 1)
        prenms <- nms[seq(1, pos - 1)]

      postnms <- nms[seq(pos + 1, length(nms))]

      nmv <- c(prenms, "VAR1", "VAR2", "DIFF", postnms)
      ret <- ret[ , nmv]

    } else if (shape == "long") {

      nms <- names(dt)
      rnms <- sub("..diff", "DIFF", nms, fixed = TRUE)
      ret <- dt
      names(ret) <- rnms


    } else {

      ret <- dt
    }

  }


  return(ret)

}

# A function to replace temporary variable names with real ones
fix_var_names <- function(dat, varnms, varlbls, shp, dnam) {

  ret <- dat
  if (!is.null(varnms) & !is.null(varlbls)) {

    lkp <- varlbls
    names(lkp) <- varnms

    if (shp == "long" & dnam == "TTests") {

      nms <- names(dat)
      nnms <- c()

      for (i in seq_len(length(nms))) {

        if (nms[i] %in% names(lkp)) {
          nnms[i] <- lkp[nms[i]]
        } else {
          nnms[i] <- nms[i]
        }
      }

      names(ret) <- nnms

    } else if (shp == "stacked" & dnam == "TTests") {

      nms <- names(dat)
      if ("VAR" %in% nms) {
        ret[["VAR"]] <- lkp[ret[["VAR"]]]
      }
    }
  }

  return(ret)
}


# Pass a vector of strings and get back a list of formulas
get_formulas <- function(models) {

  ret <- list()
  nms <- names(models)

  cnt <- 1

  for (ml in models) {

    s1 <- trimws(strsplit(ml, "=", fixed = TRUE)[[1]])

    dv <- s1[1]

    s2 <- trimws(strsplit(s1[2], " ", fixed = TRUE)[[1]])

    iv <- paste(s2, collapse = "+")

    if (length(nms) > 0 && !is.na(nms[cnt]) && nms[cnt] != "")
      ret[[nms[cnt]]] <- formula(paste(dv, "~", iv))
    else
      ret[[length(ret) + 1]] <- formula(paste(dv, "~", iv))

    cnt <- cnt + 1
  }

  return(ret)
}


get_obs <- function(data, formula) {

  vrs <- get_vars(formula)

  tvrs <- c(vrs$dvar, vrs$ivar)


  naobs <- is.na(data[[tvrs[1]]])

  for (i in seq_len(length(tvrs) - 1)) {

    v2 <- is.na(data[[tvrs[i + 1]]])

    naobs <- naobs | v2
  }

  tobs <- nrow(data)
  mobs <- sum(naobs)
  uobs <- tobs - mobs

  lbls <- c("Number of Observations Read",
            "Number of Observations Used",
            "Number of Observations with Missing Values")

  if (mobs > 0) {
    obs <- c(tobs, uobs, mobs)

  } else {

    obs <- c(tobs, uobs)
    lbls <- lbls[1:2]
  }

  ret <- data.frame(stub = lbls, NOBS = obs)

}


get_vars <- function(formula) {

  cf <- as.character(formula)

  dvar <- cf[2]

  ivar <- trimws(strsplit(cf[3], "+", fixed = TRUE)[[1]])

  ret <- list(dvar = dvar, ivar = ivar)

  return(ret)
}


get_valid_obs <- function(data, formula) {

  # Filter on the model variables, not the model terms
  if (is.character(formula))
    formula <- stats::as.formula(formula)

  tvrs <- intersect(all.vars(formula), names(data))

  naobs <- rep(TRUE, nrow(data))

  for (v in tvrs)
    naobs <- naobs & !is.na(data[[v]])

  if (nrow(data) > 0)
    ret <- data[naobs, ]
  else
    ret <- data



  return(ret)

}

# Remove factors from output data frames.
# The factors are added by the order parameter to sort the class
# values correctly.
#' @noRd
clear_factors <- function(res, class) {

  # Clear out factors from output datasets
  if (!is.null(class)) {
    if (length(class) > 1) {
      cvect <- paste0("CLASS", seq(1, length(class)))
    } else {
      cvect <- "CLASS"
    }

    for (cnm in cvect) {
      for (nm in names(res)) {
        if (grepl("Statistics", nm, fixed = TRUE)) {
          if (is.factor(res[[nm]][[cnm]])) {
            lbl <- attr(res[[nm]][[cnm]], "label")
            res[[nm]][[cnm]] <- as.character(res[[nm]][[cnm]])
            attr(res[[nm]][[cnm]], "label") <- lbl
          }
        }
        if (grepl("ConfLimits", nm, fixed = TRUE)) {
          if (is.factor(res[[nm]][[cnm]])) {
            lbl <- attr(res[[nm]][[cnm]], "label")
            res[[nm]][[cnm]] <- as.character(res[[nm]][[cnm]])
            attr(res[[nm]][[cnm]], "label") <- lbl
          }
        }
      }
    }
  }

  return(res)

}


# Sassy-r NSE
#' @noRd
resolve_arg <- function(arg, type = c("character", "NULL")) {

  call <- match.call()
  if (!"arg" %in% names(call)) {
    stop("Argument 'arg' is missing.", call. =  FALSE)
  }

  if (!is.character(type)) {
    stop("'type' must be a character vector.", call. = FALSE)
  }

  valid_modes <- c("character", "double", "integer", "NULL")

  if (!all(type %in% valid_modes)) {
    stop("'type' must contain valid mode values.", call. = FALSE)
  }

  expr <- eval.parent(substitute(substitute(arg)))
  expr_str <- paste(deparse(expr, width.cutoff = 500L), collapse = " ")

  value <- tryCatch(arg, error = function(e) e)

  res <- if (!inherits(value, "error") && typeof(value) %in% type) value else expr_str

  return(res)
}

# Subset data
#' @noRd
subset_data <- function(data, where = NULL) {

  if (!is.data.frame(data)) {
    stop("'data' must be a data.frame.", call. = FALSE)
  }

  if (is.null(where)) {
    return(data)
  }

  if (!is.expression(where)) {
    stop("'where' must be an expression.", call. = FALSE)
  }

  if (length(where) != 1L) {
    stop("'where' must be an expression of length 1.", call. = FALSE)
  }

  rows <- tryCatch(
    eval(where, envir = data),
    error = function(e)
      stop("Error evaluating 'where': ", e$message, call. = FALSE)
  )

  if (!is.logical(rows)) {
    stop("'where' must evaluate to a logical vector.", call. = FALSE)
  }

  if (length(rows) != nrow(data)) {
    stop("'where' must evaluate to a logical vector with length equal to nrow(data).", call. = FALSE)
  }

  res <- copy.attributes(data, data[rows, , drop = FALSE])

  return(res)
}

# For a given keep/drop parameter, select the vector that aligns
# with a particular table request. If the parameter is not a list,
# it is assumed to apply to all table requests, and is returned as-is.
# If it is a list, the vector is matched by table name first, falling
# back to positional matching for any unnamed list elements.
get_table_vector <- function(vec, nm, idx) {

  if (is.null(vec) || !is.list(vec)) {
    return(vec)
  }

  nms <- names(vec)
  if (is.null(nms)) {
    nms <- rep("", length(vec))
  }

  # Fill in missing names with positional sequence number
  for (k in seq_along(nms)) {
    if (is.na(nms[k]) || nms[k] == "") {
      nms[k] <- as.character(k)
    }
  }
  names(vec) <- nms

  ret <- NULL
  if (!is.null(nm) && nm %in% nms) {
    ret <- vec[[nm]]
  } else if (!is.null(idx) && !is.na(idx) && as.character(idx) %in% nms) {
    ret <- vec[[as.character(idx)]]
  }

  return(ret)
}

keep_data <- function(data, keep = NULL) {

  datIsLst <- FALSE
  keepIsLst <- FALSE

  if (!"data.frame" %in% class(data) & is.list(data) == TRUE) {
    datIsLst <- TRUE
  }

  if (is.list(keep)) {
    keepIsLst <- TRUE
  }

  if (!is.null(keep)) {

    if (datIsLst == FALSE & keepIsLst == FALSE) {
      nms <- names(data)
      ret <- data[, keep[keep %in% nms], drop = FALSE]
    } else if (datIsLst == FALSE & keepIsLst == TRUE) {

      stop("Keep vectors not aligned with table specifications.")

    } else if (datIsLst == TRUE & keepIsLst == FALSE) {

      ret <- data
      for (idx in seq(1, length(data))) {
        nms <- names(ret[[idx]])

        ret[[idx]] <- ret[[idx]][, keep[keep %in% nms], drop = FALSE]
      }

    } else if (datIsLst == TRUE & keepIsLst == TRUE) {

      ret <- data

      # Get names
      dnms <- names(ret)
      knms <- names(keep)

      # Create sequences for missing names
      dseq <- seq(1, length(ret))
      kseq <- seq(1, length(keep))

      # If there are no names, use sequences
      if (is.null(dnms)) {
        dnms <- as.character(dseq)
      }
      if (is.null(knms)) {
        knms <- as.character(kseq)
      }

      # If some names are missing,
      # replace missing names with sequence number
      for (idx in seq(1, length(data))) {
        if (dnms[idx] == "") {
          dnms[idx] <- as.character(dseq[idx])
        }

        if (knms[idx] == "") {
          knms[idx] <- as.character(kseq[idx])
        }
      }

      # Assign corrected names
      names(ret) <- dnms
      names(keep) <- knms

      # For each dataset, map keep vector and subset
      for (idx in seq(1, length(data))) {

        nm <- dnms[idx]
        kp <- keep[[nm]]

        dfnms <- names(ret[[nm]])
        ret[[nm]] <- ret[[nm]][, kp[kp %in% dfnms], drop = FALSE]
      }

      # Restore names
      names(ret) <- names(data)

    }
  } else {
    ret <- data
  }



  return(ret)
}

drop_data <- function(data, drop = NULL) {

  datIsLst <- FALSE
  dropIsLst <- FALSE

  if (!"data.frame" %in% class(data) & is.list(data) == TRUE) {
    datIsLst <- TRUE
  }

  if (is.list(drop)) {
    dropIsLst <- TRUE
  }

  if (!is.null(drop)) {

    if (datIsLst == FALSE & dropIsLst == FALSE) {
      nms <- names(data)
      ret <- data[, !nms %in% drop, drop = FALSE]
    } else if (datIsLst == FALSE & dropIsLst == TRUE) {

      stop("Drop vectors not aligned with table specifications.")

    } else if (datIsLst == TRUE & dropIsLst == FALSE) {

      ret <- data
      for (idx in seq(1, length(data))) {
        nms <- names(ret[[idx]])

        ret[[idx]] <- ret[[idx]][, !nms %in% drop, drop = FALSE]
      }

    } else if (datIsLst == TRUE & dropIsLst == TRUE) {

      ret <- data

      # Get names
      dnms <- names(ret)
      knms <- names(drop)

      # Create sequences for missing names
      dseq <- seq(1, length(ret))
      kseq <- seq(1, length(drop))

      # If there are no names, use sequences
      if (is.null(dnms)) {
        dnms <- as.character(dseq)
      }
      if (is.null(knms)) {
        knms <- as.character(kseq)
      }

      # If some names are missing,
      # replace missing names with sequence number
      for (idx in seq(1, length(data))) {
        if (dnms[idx] == "") {
          dnms[idx] <- as.character(dseq[idx])
        }

        if (knms[idx] == "") {
          knms[idx] <- as.character(kseq[idx])
        }
      }

      # Assign corrected names
      names(ret) <- dnms
      names(drop) <- knms

      # For each dataset, map drop vector and subset
      for (idx in seq(1, length(data))) {

        nm <- dnms[idx]
        dp <- drop[[nm]]

        dfnms <- names(ret[[nm]])
        ret[[nm]] <- ret[[nm]][, !dfnms %in% dp, drop = FALSE]
      }

      # Restore names
      names(ret) <- names(data)

    }
  } else {
    ret <- data
  }



  return(ret)
}


rename_data <- function(data, rename = NULL) {

  datIsLst <- FALSE
  renameIsLst <- FALSE

  if (!"data.frame" %in% class(data) & is.list(data) == TRUE) {
    datIsLst <- TRUE
  }

  if (is.list(rename)) {
    renameIsLst <- TRUE
  }

  if (!is.null(rename)) {

    if (datIsLst == FALSE & renameIsLst == FALSE) {

      ret <- data
      nms <- names(ret)
      mtch <- match(names(rename), nms)
      vmtch <- !is.na(mtch)
      nms[mtch[vmtch]] <- rename[vmtch]
      names(ret) <- nms

    } else if (datIsLst == FALSE & renameIsLst == TRUE) {

      stop("Rename vectors not aligned with table specifications.")

    } else if (datIsLst == TRUE & renameIsLst == FALSE) {

      ret <- data
      for (idx in seq(1, length(data))) {
        nms <- names(ret[[idx]])

        mtch <- match(names(rename), nms)
        vmtch <- !is.na(mtch)
        nms[mtch[vmtch]] <- rename[vmtch]
        names(ret[[idx]]) <- nms
      }

    } else if (datIsLst == TRUE & renameIsLst == TRUE) {

      ret <- data

      # Get names
      dnms <- names(ret)
      knms <- names(rename)

      # Create sequences for missing names
      dseq <- seq(1, length(ret))
      kseq <- seq(1, length(rename))

      # If there are no names, use sequences
      if (is.null(dnms)) {
        dnms <- as.character(dseq)
      }
      if (is.null(knms)) {
        knms <- as.character(kseq)
      }

      # If some names are missing,
      # replace missing names with sequence number
      for (idx in seq(1, length(data))) {
        if (dnms[idx] == "") {
          dnms[idx] <- as.character(dseq[idx])
        }

        if (knms[idx] == "") {
          knms[idx] <- as.character(kseq[idx])
        }
      }

      # Assign corrected names
      names(ret) <- dnms
      names(rename) <- knms

      # For each dataset, map rename vector and apply
      for (idx in seq(1, length(data))) {

        nm <- dnms[idx]
        rn <- rename[[nm]]

        dfnms <- names(ret[[nm]])
        mtch <- match(names(rn), dfnms)
        vmtch <- !is.na(mtch)
        dfnms[mtch[vmtch]] <- rn[vmtch]
        names(ret[[nm]]) <- dfnms
      }

      # Restore names
      names(ret) <- names(data)

    }
  } else {
    ret <- data
  }

  return(ret)
}


fmt_col <- function(vct, len) {

  v1 <- vct[!is.na(vct)]

  vl <- as.character(v1)

  pos <- regexpr(".", vl, fixed = TRUE)

  ics <- substring(vl, 1, pos)

  flen <- max(nchar(ics))

  if (flen < len) {
    ret <- paste0("%.", len - flen, "f")
  } else {
    ret <- paste0("best", len)
  }


  return(ret)

}


# Binning Experiments -----------------------------------------------------



# pretty_custom <- function(x, n = 7) {
#   # Handle edge case: empty or constant vector
#   if (length(x) == 0) return(numeric(0))
#   rng <- range(x, na.rm = TRUE)
#   if (rng[1] == rng[2]) return(rng[1])
#
#   # 1. Calculate the raw interval size
#   raw_range <- rng[2] - rng[1]
#   raw_step <- raw_range / (n - 1)
#
#   # 2. Normalize step to a value between 1 and 10 (base 10)
#   magnitude <- 10^floor(log10(raw_step))
#   normalized_step <- raw_step / magnitude
#
#   # 3. Choose the "nicest" snap point
#   # Common 'pretty' steps are 1, 2, 2.5, 5, and 10
#   nice_steps <- c(1, 2, 2.5, 5, 10)
#   actual_step <- nice_steps[which.min(abs(nice_steps - normalized_step))] * magnitude
#
#   # 4. Find the start and end points (aligned with the step size)
#   start <- floor(rng[1] / actual_step) * actual_step
#   end <- ceiling(rng[2] / actual_step) * actual_step
#
#   # 5. Generate the sequence
#   return(seq(from = start, to = end, by = actual_step))
# }

# pretty_centered <- function(x, n = 7) {
#   if (length(x) == 0) return(numeric(0))
#
#   rng <- range(x, na.rm = TRUE)
#   mu  <- mean(x, na.rm = TRUE)
#
#   # 1. Calculate the ideal step size to cover the range in ~n steps
#   raw_range <- diff(rng)
#   raw_step  <- raw_range / (n - 1)
#
#   # 2. Normalize step to "nice" intervals (1, 2, 2.5, 5, 10)
#   magnitude <- 10^floor(log10(raw_step))
#   normalized_step <- raw_step / magnitude
#   nice_steps <- c(1, 2, 2.5, 5, 10)
#   actual_step <- nice_steps[which.min(abs(nice_steps - normalized_step))] * magnitude
#
#   # 3. Center the 4th breakpoint at the "nice" value closest to the mean
#   # This ensures the middle of our sequence is a clean number near the mean
#   center_point <- round(mu / actual_step) * actual_step
#
#   # 4. Calculate how many steps we need to cover the data below and above the center
#   # We want roughly (n-1)/2 steps on each side
#   side_steps <- ceiling((n - 1) / 2)
#
#   # 5. Generate sequence centered on our nice mean-proxy
#   breaks <- seq(
#     from = center_point - (side_steps * actual_step),
#     to   = center_point + (side_steps * actual_step),
#     by   = actual_step
#   )
#
#   # 6. Optional: Expand if the range isn't fully covered due to centering
#   while(min(breaks) > rng[1]) breaks <- c(min(breaks) - actual_step, breaks)
#   while(max(breaks) < rng[2]) breaks <- c(breaks, max(breaks) + actual_step)
#
#   return(breaks)
# }



# pretty_sas <- function(x, n = 7) {
#
#   # x <- c(-.8, 78)
#
#   rng <- range(x, na.rm = TRUE)
#   mu  <- mean(x, na.rm = TRUE)
#   dif <-  diff(rng)
#   step <- dif / (n - 1)
#
#   magnitude <- 10^floor(log10(step))
#   base <- magnitude / 2
#   pstep <- base*ceiling(step/base)
#
#   bars <- ceiling(dif / pstep)
#
#   pbars <- seq(0, bars * pstep, pstep)
#
#   fbars <- pbars + rng[1]
#
#   ret <- base * floor(fbars/base)
#
#   return(ret)
# }



# Text Functions ----------------------------------------------------------



#' @description Estimate number of wraps based on text, width, and a font.
#' @import graphics
#' @import withr
#' @noRd
get_text_width <- function(txt, font = "arial", font_size = 12,
                           multiplier = .975) {


  f <- "mono"
  if (tolower(font) == "arial")
    f <- "sans"
  else if (tolower(font) == "times")
    f <- "serif"

  un <- "inches"

  ret <- 0

 withr::with_pdf(NULL, {
   par(family = f, ps = font_size)
   if (length(txt) > 0) {
     ret <- strwdth(txt, un) * multiplier
   }
 })


  return(ret)
}

# Vectorized function to calculate string width.
# Error and warning handling is necessary because the string
# may contain special characters which generate errors/warnings
# in the strwidth() function.
strwdth <- Vectorize(function(wrd, un) {

  if (is.na(wrd)) {
    ret <- 0
  } else {

    ret <- tryCatch({

      suppressWarnings(strwidth(wrd, units = un))



    }, error = function(cond) {

      suppressWarnings(strwidth("a", units = un)) * nchar(wrd)

    })
  }

  return(ret)
}, USE.NAMES = FALSE, SIMPLIFY = TRUE)



get_line_count <- function(vct, fs = 12) {

  mxwdth <- 0

  if ("factor" %in% class(vct)) {
    vct <- as.character(vct)
  }

  # Break by user-defined line feeds
  spl <- strsplit(vct, "\n", fixed = TRUE)

  for (idx in seq_along(spl)) {

    ln <- spl[[idx]]

    # Get widths of each item in vector
    wdths <- get_text_width(ln, font_size = fs, multiplier = 1)

    # Get max width
    if (max(wdths) > mxwdth) {
      mxwdth <- max(wdths)
    }
  }

  # Estimate number of lines needed
  # 5 is approximate number of lines per inch
  ret <- mxwdth * 5

  return(ret)

}



# Fit string to specified width, break lines as needed,
# and return how many lines are required.
# Also account for user-defined line breaks, and single words
# that are too big to fit in available width.
#' @noRd
fit_width <- function(str, wdth) {

  # browser()

  if (is.character(str) == FALSE) {
    str <- as.character(str)
  }

  # Return vector and line count
  lst <- list()
  mxlns <- 0

  # Width of space. Needed below.
  spc <- get_text_width(" ", font_size = 12, multiplier = .9)

  # Get User-split sections
  spl <- strsplit(str, "\n", fixed = TRUE)

  # Vector loop
  for (idx1 in seq_along(spl)) {

    # Get segment
    seg <- spl[[idx1]]

    # Get width of segment
    wseg <- get_text_width(seg, font_size = 12, multiplier = .9)

    # One line of input vector
    ln <- c()

    # User-split loop
    for (idx2 in seq_along(seg)) {

      # If segment width is in bounds, just add it
      if (wseg[idx2] <= wdth) {

        ln <- append(ln, seg[idx2])
      } else {

        # browser()

        # Break into words
        wrds <- strsplit(seg[idx2], " ", fixed = TRUE)[[1]]

        # Width of words.
        wwrds <- get_text_width(wrds, font_size = 12, multiplier = .9)

        ln2 <- c()
        pos <- 1

        for (idx3 in seq_along(wrds)) {

          # Proposed sequence
          psq <- seq(pos, idx3)

          # Proposed width
          tw <- sum(wwrds[psq]) + ((length(psq) - 1) * spc)

          # Check proposed width
          if (tw > wdth) {

            # Even one word too big
            if (idx3 - pos == 0) {

              ln2 <- c(ln2, force_width(wrds[idx3], wdth))
              pos <- idx3

            } else {

              ln2 <- c(ln2, paste(wrds[seq(pos, idx3 - 1)], collapse = " "))
              pos <- idx3

              if (idx3 == length(wrds)) {

                # Append last section
                if (wwrds[idx3] > wdth) {
                  ln2 <- c(ln2, force_width(wrds[idx3], wdth))
                } else {
                  ln2 <- c(ln2, wrds[idx3])
                }
              }
            }


          } else if (idx3 == length(wrds)) {

            # Append last section
            ln2 <- c(ln2, paste(wrds[seq(pos, idx3)], collapse = " "))
          }
        }

        ln <- append(ln, ln2)

      }
    }

    # Update max lines
    if (length(ln) > mxlns) {
      mxlns <- length(ln)
    }

    # Append to return vector
    lst[[length(lst) + 1]] <- ln

  }

  # Collapse list of vectors into single vector
  vct <- c()
  for (idx4 in seq_along(lst)) {

    # Get vector
    mvct <- lst[[idx4]]

    # Add empty strings if needed
    if (length(mvct) < mxlns) {
      mvct <- append(mvct, rep("", mxlns - length(mvct)))
    }

    # Collapse to one string
    ln <- paste0(mvct, collapse = "\n")
    vct <- append(vct, ln)
  }


  ret <- list(Vector = vct, Lines = mxlns)


  return(ret)
}


# Fit string to specified width, put ... if needed
#' @noRd
force_width <- function(str, wdth) {

  # Split every character
  spl <- strsplit(str, "", fixed = TRUE)

  # Return vector
  ret <- c()

  for (idx in seq_along(spl)) {

    # Get characters for one vector item
    chrs <- spl[[idx]]

    # Get width of each character
    wdths <- get_text_width(chrs, font_size = 12, multiplier = .9)

    # Get cumulative sum
    cwdths <- cumsum(wdths)

    # Figure out which characters are in bounds
    ib <- cwdths <= wdth

    # Determine if string needs truncating
    if (all(ib == TRUE)) {
      ret <- append(ret, str[idx])
    } else {

      # Filter out characters
      tmp1 <- chrs[ib]

      # Remove last three characters
      if (length(tmp1) > 3) {
        tmp2 <- tmp1[seq(1, length(tmp1) - 3)]
      } else {
        tmp2 <- tmp1
      }

      # Collapse into single string
      tmp3 <- paste0(tmp2, collapse = "")

      # Add dots
      if (length(tmp1) > 3) {
        tmp4 <- paste0(tmp3, "...")
      } else {
        tmp4 <- tmp3
      }

      # Append to return vector
      ret <- append(ret, tmp4)

    }

  }


  return(ret)
}







# The SAS ZETA= option: the tolerance used when checking whether a contrast or
# estimate is estimable.  Matches the default of sasLM's estmb().
#' @noRd
get_zeta <- function(opts) {

  ret <- 1e-8

  if (!is.null(opts)) {
    nms <- tolower(names(opts))

    if ("zeta" %in% nms) {

      ret <- opts[["zeta"]]

      if (!is.numeric(ret))
        ret <- as.numeric(ret)
    }
  }

  return(ret)
}


# The SAS SINGULAR= option: the tolerance used when checking a design matrix
# column for a linear dependency on the columns before it.
#' @noRd
get_singular <- function(opts) {

  ret <- 1e-8

  if (!is.null(opts)) {
    nms <- tolower(names(opts))

    if ("singular" %in% nms) {

      ret <- opts[["singular"]]

      if (!is.numeric(ret))
        ret <- as.numeric(ret)
    }
  }

  return(ret)
}


# Turn a labeled numeric matrix into the stub + columns data frame shape the
# report functions expect.  Used for the SAS matrix displays (X'X and its
# inverse), which have no natural stub column of their own: the row names are
# the stub.
#' @import fmtr
#' @noRd
matrix_table <- function(mat, stub_label = "Parameter") {

  rn <- rownames(mat)

  if (is.null(rn))
    rn <- as.character(seq_len(nrow(mat)))

  ret <- data.frame(stub = rn, stringsAsFactors = FALSE)
  ret <- cbind(ret, as.data.frame(unname(unclass(mat))))

  names(ret) <- c("stub", colnames(mat))
  rownames(ret) <- NULL

  lbls <- list(stub = stub_label)
  fmts <- list()

  for (nm in colnames(mat))
    fmts[[nm]] <- "best12"

  labels(ret) <- lbls
  formats(ret) <- fmts

  return(ret)
}


# The permutation that puts the design matrix columns into SAS parameter order:
# within each interaction, by the level order of each factor, the first factor
# varying slowest.  Columns only move within their own effect.
#' @noRd
sas_col_order <- function(mm, data) {

  cn <- colnames(mm$X)
  perm <- seq_along(cn)

  for (eff in names(mm$termIndices)) {

    vars <- strsplit(eff, ":", fixed = TRUE)[[1]]
    if (length(vars) < 2)
      next

    pos <- mm$termIndices[[eff]]
    parts <- strsplit(cn[pos], ":", fixed = TRUE)

    # One sort key per factor: the level index, or 0 for a continuous variable
    keys <- lapply(seq_along(vars), function(i) {

      v <- vars[i]
      x <- data[[v]]
      if (is.null(x) || (is.numeric(x) && !is.factor(x)))
        return(rep(0L, length(pos)))

      lvl <- vapply(parts, function(p) substring(p[i], nchar(v) + 1),
                    character(1))
      match(lvl, levels(as.factor(x)))
    })

    if (any(vapply(keys, anyNA, logical(1))))
      next

    perm[pos] <- pos[do.call(order, unname(keys))]
  }

  return(perm)
}


# The sasLM model matrix with its SAS parameter order attached as mm$perm:
# mm$perm[k] is the column holding the k-th parameter in SAS order.
# keep_order keeps the effects in the order the model was written.
#' @import sasLM
#' @noRd
glm_model_matrix <- function(formula, data, keep_order = FALSE) {

  mm <- ModelMatrix(formula, data, KeepOrder = keep_order)
  mm$perm <- sas_col_order(mm, data)

  return(mm)
}


# Whether effect e2 contains effect e1, by the SAS PROC GLM rule: e2 has every
# variable of e1, both have the same continuous variables, and e2 has more
# class variables.
#' @noRd
sas_contains <- function(e2, e1, class) {

  v1 <- strsplit(e1, ":", fixed = TRUE)[[1]]
  v2 <- strsplit(e2, ":", fixed = TRUE)[[1]]

  return(e1 != e2 &&
           all(v1 %in% v2) &&
           setequal(setdiff(v1, class), setdiff(v2, class)) &&
           sum(v2 %in% class) > sum(v1 %in% class))
}


# The Type II hypothesis rows for every effect under the SAS containment rule:
# X_E' M X, where M projects out the intercept and every other effect that
# does not contain E.  Rows sit at E's own parameter positions.
#' @import sasLM
#' @noRd
sas_e2 <- function(mm, class, eps = 1e-8) {

  X <- mm$X
  ti <- mm$termIndices
  effs <- setdiff(names(ti), "(Intercept)")

  E <- matrix(0, ncol(X), ncol(X), dimnames = list(NULL, colnames(X)))

  for (e in effs) {

    adj <- effs[!vapply(effs, function(o) o == e || sas_contains(o, e, class),
                        logical(1))]
    c0 <- unlist(ti[c(intersect("(Intercept)", names(ti)), adj)],
                 use.names = FALSE)

    MX <- X
    if (length(c0) > 0) {
      X0 <- X[, c0, drop = FALSE]
      MX <- X - X0 %*% G2SWEEP(crossprod(X0), Augmented = FALSE, eps = eps) %*%
        crossprod(X0, X)
    }

    E[ti[[e]], ] <- crossprod(X[, ti[[e]], drop = FALSE], MX)
  }

  return(E)
}


# Put a sasLM::GLM() result into SAS terms: Type II under the SAS containment
# rule, parameter estimates fit in SAS parameter order with SAS labels, and
# interaction sources spelled with "*".  Weights are applied as sasLM::GLM()
# applies them.
#' @import sasLM
#' @noRd
sas_glm <- function(glm, model, data, class = NULL, weight = NULL,
                    eps = 1e-8) {

  srwi <- if (is.null(weight)) 1 else sqrt(data[[weight]])
  y <- srwi * stats::model.frame(model, data)[, 1]

  if (!is.null(glm[["Type II"]])) {

    mm <- glm_model_matrix(model, data)
    mm$X <- srwi * mm$X
    rw <- lfit(mm, y, eps = eps)
    E2 <- sas_e2(mm, class, eps = eps)

    # A matrix with class "anova"; assign into the bare matrix
    T2 <- unclass(glm[["Type II"]])
    for (e in intersect(rownames(T2), names(mm$termIndices))) {
      cs <- cSS(E2[mm$termIndices[[e]], , drop = FALSE], rw, eps = eps)
      T2[e, colnames(cs)] <- as.numeric(cs[1, ])
    }
    class(T2) <- "anova"
    glm[["Type II"]] <- T2
  }

  if (!is.null(glm$Parameter)) {

    mm <- glm_model_matrix(model, data, keep_order = TRUE)
    cn <- colnames(mm$X)[mm$perm]
    x <- list(X = srwi * mm$X[, mm$perm, drop = FALSE])

    P <- sumREG(lfit(x, y, eps = eps), x$X)

    lbls <- character(length(cn))
    for (eff in names(mm$termIndices))
      lbls[mm$termIndices[[eff]]] <-
        estimable_labels(eff, cn[mm$termIndices[[eff]]])
    rownames(P) <- lbls

    glm$Parameter <- P
  }

  for (ty in c("Type I", "Type II", "Type III")) {
    if (!is.null(glm[[ty]]))
      rownames(glm[[ty]]) <- gsub(":", "*", rownames(glm[[ty]]), fixed = TRUE)
  }

  return(glm)
}


# Build the SAS estimable function table (e1, e2, e3) from a basis with one
# hypothesis row per parameter: one row per parameter, one column per effect,
# each cell an expression in the free symbols L1, L2, ...  The basis is put in
# SAS parameter order, and each effect's rows are row reduced with pivots on
# the effect's own columns in level order.
#' @noRd
estimable_table <- function(E, mm, eps = 1e-8) {

  perm <- mm$perm
  E <- E[perm, perm, drop = FALSE]

  pn <- colnames(mm$X)[perm]
  ti <- mm$termIndices
  effs <- names(ti)[names(ti) != "(Intercept)"]

  # SAS row labels
  stub <- character(length(pn))
  for (eff in names(ti))
    stub[ti[[eff]]] <- estimable_labels(eff, pn[ti[[eff]]])

  ret <- data.frame(stub = stub, stringsAsFactors = FALSE)

  for (eff in effs) {

    pos <- ti[[eff]]
    B <- E[pos, , drop = FALSE]
    tol <- eps * max(1, max(abs(B)))

    # Gauss-Jordan with pivots restricted to this effect's columns
    piv <- integer(0)
    for (j in pos) {

      r <- length(piv)
      if (r == nrow(B))
        break

      cand <- (r + 1):nrow(B)
      k <- cand[which.max(abs(B[cand, j]))]
      if (abs(B[k, j]) < tol)
        next

      B[c(r + 1, k), ] <- B[c(k, r + 1), ]
      r <- r + 1
      B[r, ] <- B[r, ] / B[r, j]
      for (i in seq_len(nrow(B))[-r])
        B[i, ] <- B[i, ] - B[i, j] * B[r, ]

      piv <- c(piv, j)
    }

    B <- B[seq_along(piv), , drop = FALSE]

    ret[[gsub(":", "*", eff, fixed = TRUE)]] <-
      vapply(seq_along(pn), function(j) estimable_cell(B[, j], piv, eps),
             character(1))
  }

  labels(ret) <- list(stub = "Effect")

  return(ret)
}


# Render one cell of an estimable function table: the sum of coef * Lk over
# the free symbols, written the SAS way.
#' @noRd
estimable_cell <- function(coefs, piv, eps = 1e-8) {

  trms <- character(0)

  for (i in seq_along(piv)) {

    co <- coefs[i]
    sym <- paste0("L", piv[i])

    if (abs(co - 1) < eps)
      trm <- sym
    else if (abs(co + 1) < eps)
      trm <- paste0("-", sym)
    else {
      val <- estimable_num(abs(co))
      if (val == "0")
        next
      trm <- paste0(if (co < 0) "-" else "", val, "*", sym)
    }

    if (length(trms) > 0 && substr(trm, 1, 1) != "-")
      trm <- paste0("+", trm)

    trms <- c(trms, trm)
  }

  if (length(trms) == 0)
    return("0")

  return(paste(trms, collapse = ""))
}


# Format a non-negative coefficient the way SAS writes it in an estimable
# function: 6 characters wide, trailing zeros dropped.  The sign is written by
# the caller.
#' @noRd
estimable_num <- function(x) {

  intd <- if (x >= 1) floor(log10(x)) + 1 else 1
  dec <- max(0, 6 - intd - 1)
  rx <- round(x, dec)

  # Rounding can carry into a new integer digit (9.99996 -> 10)
  if (rx >= 10^intd)
    dec <- max(0, dec - 1)

  val <- formatC(rx, format = "f", digits = dec)

  if (grepl(".", val, fixed = TRUE))
    val <- sub("\\.?0+$", "", val)

  return(val)
}


# SAS row labels for the parameters of one effect: the effect name, then the
# levels separated by spaces.
#' @noRd
estimable_labels <- function(eff, cols) {

  if (eff == "(Intercept)")
    return(rep("Intercept", length(cols)))

  vars <- strsplit(eff, ":", fixed = TRUE)[[1]]
  efflbl <- paste(vars, collapse = "*")

  vapply(cols, function(cl) {
    parts <- strsplit(cl, ":", fixed = TRUE)[[1]]
    lvls <- substring(parts, nchar(vars) + 1)
    lvls <- lvls[lvls != ""]
    if (length(lvls) == 0)
      efflbl
    else
      paste(efflbl, paste(lvls, collapse = " "))
  }, character(1), USE.NAMES = FALSE)
}

Try the procs package in your browser

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

procs documentation built on Nov. 2, 2026, 5:06 p.m.