R/getLkDirectAncestors.R

Defines functions getLkDirectAncestors

Documented in getLkDirectAncestors

#' Get the direct ancestors of selected animals
#'
## Copyright(c) 2017-2024 R. Mark Sharp
## This file is part of nprcgenekeepr
#' Gets direct ancestors from labkey \code{study} schema and \code{demographics}
#' table.
#'
#' @return data.frame with pedigree structure having all of the direct ancestors
#' for the Ids provided.
#'
#' @param ids character vector with Ids.
#' @import futile.logger
#' @importFrom stringi stri_c
#' @export
#' @examples
#' \donttest{
#' # Requires LabKey connection
#' library(nprcgenekeepr)
#' ## Have to a vector of focal animals
#' focalAnimals <- c("1X2701", "1X0101")
#' suppressWarnings(getLkDirectAncestors(ids = focalAnimals))
#' }
getLkDirectAncestors <- function(ids) {
  siteInfo <- getSiteInfo()
  colSet <- siteInfo$lkPedColumns
  source <- " generated by getDemographics in getLkDirectAncestors: "
  pedSourceDf <- tryCatch(getDemographics(colSelect = colSet),
    warning = function(wCond) {
      flog.debug(stri_c("Warning", source, wCond),
        name = "nprcgenekeepr"
      )
      return(NULL)
    },
    error = function(eCond) {
      flog.debug(stri_c("Error", source, eCond),
        name = "nprcgenekeepr"
      )
      return(NULL)
    }
  )
  if (is.null(pedSourceDf)) {
    return(NULL)
  }
  names(pedSourceDf) <- siteInfo$mapPedColumns
  parents <- ids
  len <- length(parents)
  ancestorsDf <- pedSourceDf[pedSourceDf$id %in% ids, ]
  while (len > 0L) {
    parents <- getParents(pedSourceDf, parents)
    len <- length(parents)
    if (len > 0L) {
      ancestorsDf <- rbind(ancestorsDf,
        pedSourceDf[pedSourceDf$id %in% parents, ],
        stringsAsFactors = FALSE
      )
    }
  }
  ancestorsDf[!duplicated(ancestorsDf$id), ]
}

Try the nprcgenekeepr package in your browser

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

nprcgenekeepr documentation built on June 8, 2025, 10:55 a.m.