R/GroupProfiles.R

Defines functions GroupProfiles

Documented in GroupProfiles

#' @title Generate Group Profiles Based on Covariates
#'
#' @description This function calculates the mean of specified covariates for each trajectory group.
#' It first assigns each individual to a group based on the highest posterior probability,
#' then computes the average value of each provided covariate for all members of that group.
#'
#' @param sol A trajectory object returned by the \code{trajeR} function.
#' @param Y The response variable matrix, as used in the `trajeR` call.
#' @param A The time variable matrix, as used in the `trajeR` call.
#' @param X A numeric matrix or data frame of covariates for which the profiles are to be calculated.
#'   Each column represents a different covariate.
#'
#' @return A matrix where rows correspond to the covariates in `X` and columns correspond
#'   to the trajectory groups. Each cell contains the mean of a covariate for a specific group.
#' @export
#'
#' @examples
#' data <- read.csv(system.file("extdata", "CNORM2gr.csv", package = "trajeR"))
#' data <- as.matrix(data)
#' sol <- trajeR(
#'   Y = data[, 2:6], A = data[, 7:11], Risk = data[, 12, drop = FALSE],
#'   degre = c(2, 2), Model = "CNORM", Method = "L"
#' )
#' GroupProfiles(sol, Y = data[, 2:6], A = data[, 7:11], X = data[, 12, drop = FALSE])
GroupProfiles <- function(sol, Y, A, X) {
  prob <- GroupProb(sol, Y = Y, A = A, X = X)
  gr <- sapply(1:nrow(prob), function(s) {
    which.max(prob[s, ])
  })
  if (!is.matrix((X))) {
    X <- matrix(X)
  }
  tab <- c()
  for (j in 1:ncol(X)) {
    tabl <- c()
    for (i in 1:sol$groups) {
      tabl <- c(tabl, mean(X[gr == i, j]))
    }
    tab <- rbind(tab, tabl)
  }
  colnames(tab) <- paste0("Gr ", 1:sol$groups)
  rownames(tab) <- colnames(X)
  return(tab)
}

Try the trajeR package in your browser

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

trajeR documentation built on Aug. 4, 2026, 1:09 a.m.