Learn R Programming

README

R. Mark Sharp, Ph.D. 2026-10-30

nprcgenekeepr

Version 3.0.0 (2026-10-31)

Introduction

The primary goal of nprcgenekeepr is to implement Genetic Tools for Colony Management. It was initially conceived and developed as a Shiny web application at the Oregon National Primate Research Center (ONPRC) to facilitate some of the analyses they perform regularly. It has been enhanced to have more capability as a Shiny application and to expose the functions so they can be used either interactively or in R scripts.

Work on this package up to and including version 1.0 was supported in part by NIH grants P51 RR13986 to the Southwest National Primate Research Center and P51 OD011092 to the Oregon National Primate Research Center.

The application’s main functions include:

  1. Quality control of studbooks contained in text files or Excel workbooks and of pedigrees within LabKey Electronic Health Records (EHR)
  2. Creation of pedigrees from a lists of animals using the LabKey EHR integration
  3. Creation and display of an age by sex pyramid plot of the living animals within the designated pedigree
  4. Generation of Genetic Value Analysis Reports
  5. Creation of potential breeding groups with and without proscribed sex ratios and defined maximum kinships.

The application has further tabs for mate pair analysis, genetic diversity, marker genetics, potential parents, cross-center identity mapping, de-identified export, and genetic-health trends. The Colony Manager Guide article describes them.

For more information see:
A Practical Approach for Designing Breeding Groups to Maximize Genetic Diversity in a Large Colony of Captive Rhesus Macaques (Macaca mulatta) Vinson, A ; Raboin, MJ Journal Of The American Association For Laboratory Animal Science, 2015 Nov, Vol.54(6), pp.700-707 [Peer Reviewed Journal]

Installation

You can install the CRAN version of nprcgenekeepr from the R console prompt with:

install.packages("nprcgenekeepr")

You can install the development version of nprcgenekeepr from GitHub from the R console prompt with:

install.packages("devtools")
devtools::install_github(file.path("rmsharp", "nprcgenekeepr"))

All missing dependencies should be automatically installed.

Online Documentation

You can find the complete online documentation at https://rmsharp.github.io/nprcgenekeepr/.

At the top of the page are three menus to the right of the Home icon: Reference, Articles, and Changelog.

The Reference menu at the top of the page brings up the list of documentation for Data objects, Major Features and Functions, Primary interactive functions and All exposed functions.

The Articles menu brings up the list of articles and vignettes. Most are tutorials for using the package; a few, such as the validation and release engineering articles, document how the software was checked and built.

The Changelog brings up a copy of the NEWS file of the package, which records the major changes made for each version.

Running Shiny Application

The toolset available within nprcgenekeepr can be used inside standard R scripts. However, it was originally designed to be used within a Shiny application that can be started with:

library(nprcgenekeepr) # nolint: undesirable_function_linter
runGeneKeepR()

(runModularApp() also still launches the application but is deprecated in favor of runGeneKeepR().)

Summary of Major Functions

Quality Control

Studbooks maintained by breeding colonies generally contain information of varying quality. The quality control functions of the toolkit check to ensure all animals listed as parents have their own line entries, all parents have the appropriate sex listed, no animals are listed as both a sire and a dam, duplicate entries are removed, pedigree generation numbers are added, and all dates are valid dates. In addition, exit dates are added if possible and are consistent with other information such as departure dates and death dates. Ages are added from the birth and exit dates when the file has valid birth dates and no age column; the current date is used as the end point for animals with no exit date. No database connection is needed. (A connection is used only to build a pedigree from a list of animals with LabKey, described below.)

Parents with ages below a user selected threshold are identified. The user can set a minimum sire age and a minimum dam age in years, and each is used to ensure every sire or dam is at least that age on the birth date of an offspring. Leaving a field blank uses the minimum breeding age for the animal’s species; 2 years is used only when the species is missing or unknown. This check is not performed for animals with missing birth dates.

Creation of Pedigree From a List of Potential Breeders and LabKey

The user can enter a list of focal animals in a CSV file that will be used to create a pedigree containing all direct relatives (ancestors and descendants) via the labkey.selectRows function within the Rlabkey package if a database connection is provided via a configuration file and the user has read permission on a LabKey server with the demographic data in an EHR (Electronic Health Record) module. Without a database connection, the user can instead upload a pedigree file together with the list of focal animals, and the pedigree of the focal animals is built from that file (getFocalAnimalPedFromFile()).

Two configuration files are needed to use the database features of nprcgenekeepr with LabKey. The first file is named _netrc on Microsoft Windows operating systems and .netrc otherwise, allows the user to authenticate with LabKey through the LabKey API and is fully described by LabKey documentation

The second file is named _nprcgenekeepr_config on Microsoft Windows operating systems and .nprcgenekeepr_config otherwise and is the nprcgenekeepr configuration file An image of this example configuration file is included as a data object and can be loaded and viewed with the following lines of R code in the R console.

data("exampleNprcgenekeeprConfig")
View(exampleNprcgenekeeprConfig)

Display of an age by sex pyramid plot

Adapted from https://www.thoughtco.com/age-sex-pyramids-and-population-pyramids-1435272 on 20190603. Written by Matt Rosenberg. Updated May 07, 2019.

The most important demographic characteristic of a population is its age-sex structure. Age-sex pyramids (also known as population pyramids) graphically display this information to improve understanding and make comparison easy. The population pyramid sometimes has a distinctive pyramid-like shape when displaying a growing population.

How to Read the Age-Sex Graph

An age-sex pyramid breaks down a population into male and female genders and age ranges. Usually, you’ll find the left side of the pyramid graphing the male population and the right side of the pyramid displaying the female population.

Along the horizontal axis (x-axis) of a population pyramid, the graph displays the population either as a total population of that age or as a percentage of the population at that age. The center of the pyramid starts at zero population and extends out to the left for males and right for females in increasing size, or proportion of the population.

Along the vertical axis (y-axis), age-sex pyramids display age increments, from birth at the bottom to old age at the top. The application uses two-year increments by default; the Bin Size control accepts 1 to 10, and Age Unit switches between years and months.

Genetic Value Analysis Reports

The Genetic Value Analysis is a ranking scheme developed at ONPRC to indicate the relative breeding value of animals in the colony. The scheme uses the mean kinship for each animal to indicate how inter-related it is with the rest of the current breeding colony members. Genome uniqueness is used to provide an indication of whether or not an animal is likely to possess alleles at risk of being lost from the colony. Under the scheme, animals with low mean kinship or high genome uniqueness are ranked more highly.

Breeding Group Formation

One of the goals in breeding group formation is to avoid the potential for mating of closely related animals. Since behavioral concerns and housing constraints will also be taken into account in the group formation process, it is our goal to provide the largest number of animals possible from a list of candidates that can be housed together without risk of consanguineous mating. To that end, this function uses information from the Genetic Value Analysis to search for the largest combinations of animals that can be produced from a list of candidates.

The default options do not consider the sex of individuals when forming the groups, though this has likely been a consideration by the user in selecting the candidate group members. Optionally the user may select to form harem groups, which considers the sex of individuals when forming groups and restricts the number of males to one per group.

Copy Link

Version

Install

install.packages('nprcgenekeepr')

Monthly Downloads

287

Version

3.0.0

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

R. Mark Sharp

Last Published

November 1st, 2026

Functions in nprcgenekeepr (3.0.0)

applyKinshipOverrides

Apply outside-information kinship overrides to a kinship matrix
calcAge

Calculate animal ages
assignAlleles

Assign parent alleles randomly
calcFEFG

Calculate founder equivalents and founder genome equivalents
buildMarkerGenotypeMatrix

Pivot a long-format marker genotype table into a wide genotype matrix
calcA

Count each individual's rare alleles per simulation
calcFG

Calculate founder genome equivalents
backfillColonySnapshots

Rebuild earlier colony snapshots from a pedigree's birth and exit dates
appendColonySnapshot

Append a colony snapshot to a snapshot history
calcFE

Calculate founder equivalents
calcGUSE

Calculate the standard error of genome uniqueness
calcGU

Calculate genome uniqueness for each population ID
calcNeSexRatio

Calculate the demographic sex-ratio effective population size
calcGeneDiversity

Calculate gene diversity from founder genome equivalents
calcRetention

Calculate allelic retention
calcSnapshotDeltas

Compare two colony snapshots metric by metric
calcFGSE

Calculate the standard error of founder genome equivalents
calcSkewness

Calculate bias-adjusted sample skewness
calcKurtosis

Calculate bias-adjusted sample excess kurtosis
calcNeVariance

Calculate the variance effective population size
checkAncestryRules

Validate an ancestry compatibility rules table
calculateSexRatio

Calculate the sex ratio of a set of animals
checkMarkerGenotypeFile

Check a long-format multi-locus marker genotype file
checkChangedColsLst

Check a changed-columns list for non-empty fields
checkKinshipOverrides

Validate a kinship overrides table
checkErrorLst

Check an error list for non-empty fields
checkLocusMetadata

Check a locus-metadata sidecar table and classify per-locus coverage
checkGenotypeFile

Check genotype file
checkLinkageMarkerGenotypeFile

Check a long-format multi-locus marker genotype file, multiallelic-tolerant
checkCrossCenterMapping

Collect every cross-center identity-mapping problem, without stopping
computeGenomicROH

Compute genomic Runs of Homozygosity (ROH) and F_ROH
convertAncestry

Convert ancestry information to a standard code
checkSnapshotHistory

Validate a colony snapshot-history table
checkParentAge

Check parent ages against a minimum age
checkMhcHaplotypeFile

Check a wide-format MHC haplotype designation file
chooseDate

Choose the earlier or later of two dates
checkTwinRelations

Validate a twin/zygosity relations table
chooseAlleles

Combine two allele vectors by Mendelian sampling
checkRequiredCols

Check column names for required columns
checkSequenceGenotypeFile

Check a long-format sequence-derived marker genotype file
correctParentSex

Correct the sex of animals listed as a sire or dam
createColonySnapshot

Create a colony snapshot row from a genetic value report
convertDate

Convert character date columns to Date type
convertStatusCodes

Convert status indicators to a standardized code
countLoops

Count the number of loops in a pedigree tree
convertFromCenter

Convert from-center information to a logical value
countFirstOrder

Count first-order relatives
convertRelationships

Convert pairwise kinship values to relationship categories
convertSexCodes

Convert a sex indicator to a standardized code
countKinshipValues

Count kinship-value occurrences across simulated pedigrees
cumulateSimKinships

Compute kinship summary statistics across simulations
dataframe2string

Convert a data frame to a character vector
createPedTree

Create a pedigree tree (PedTree)
.markerOppositeHomozygoteCount

Count opposite-homozygote (Mendelian-conflict) loci between two genotype rows
createExampleFiles

Create example pedigree and ID-list CSV files
create_wkbk

Create an Excel workbook with worksheets
createSimKinships

Build kinship matrices from simulated pedigrees
.markerTransmissionProbability

Probability a parent transmits the reference allele
.markerFlaggedSlotPedigree

Build a local pedigree copy with each flagged (id, role) slot blanked
.markerAlleleFrequencyTable

Compute per-allele population frequency at one locus from a genotype matrix
drawPedigreeDiagram

Draw the Pedigree Browser's Diagram from a mating layout
filterKinMatrix

Filter a kinship matrix to selected IDs
fillGroupMembersWithSexRatio

Form breeding groups to match a target sex ratio
filterReport

Filter a genetic value report to selected animals
filterThreshold

Filter out kinship pairs below a threshold
.markerTwoSourceGenotypeProbability

Offspring genotype probability given two allele-transmission sources
filterPairs

Filter kinship pairs by the animals' sexes
examplePedigree

Example pedigree object (from ExamplePedigree.csv)
.parseMhcHaplotypeCalls

Parse per-animal MHC haplotype designations into a long call table
exampleNprcgenekeeprConfig

Example nprcgenekeepr configuration file (loadable)
findPedigreeNumber

Determine the pedigree number for each ID
fixColumnNames

Standardize pedigree column names
focalAnimals

Focal animal IDs from examplePedigree
findGeneration

Determine the generation number for each ID
getAncestors

Recursively collect an individual's ancestors
findLoops

Find loops in a pedigree tree
geneDrop

Simulate gene dropping through a pedigree
findOffspring

Count total offspring for each animal
getAnimalsWithHighKinship

List each animal's high-kinship relatives
finalRpt

Genetic-value report list prior to ranking
getChangedColsTab

Build the changed-columns tab panel
getDateErrorsAndConvertDatesInPed

Find date errors and convert dates in a pedigree
getConfigFileName

Get the configuration file name for the system
getCurrentAge

Calculate current age in years from a birth date
getDescendantPedigree

Reduce a pedigree to a group and its descendants
getEmptyErrorLst

Create an empty errorLst object
getDatedFilename

Prepend the date and time to a file name
getAutoIdFormat

Get the auto-generated unknown-ID format
getDemographics

Get demographic data
getBoxWhiskerDescription

Get Box and Whisker Plot Description
getIdsWithOneParent

Get ids of animals with only one parent
getFocalAnimalPedFromFile

Get a focal-animal pedigree from a pedigree file
getGVGenotype

Extract genotype data for a genetic value report
getGeneticDiversityStats

Assemble breeding-group genetic diversity heat-map statistics
getFocalAnimalPed

Get pedigree based on list of focal animals
getGVPopulation

Get the population of interest for the Genetic Value analysis
getErrorTab

Build the error-list tab panel
getFounders

Get the founder ids from a pedigree
getGenotypes

Get genotypes from file
getFileDirectRelatives

Get the direct relatives of selected animals from a pedigree file
getPedMaxAge

Get the maximum age of any animal in the pedigree
getPotentialParents

Get potential parents for animals with unknown parents
getIncludeColumns

Get the superset of report-inclusion columns
getOffspring

Get offspring to corresponding animal IDs provided
getParents

Get parents to corresponding animal IDs provided
getPossibleCols

Get possible column names for a studbook
getLkDirectAncestors

Get the direct ancestors of selected animals
getPedDirectRelatives

Get the direct relatives of selected animals from a pedigree
getPedigree

Get pedigree from file
getLkDirectRelatives

Get the direct relatives of selected animals from the LabKey EHR
getSiteInfo

Get site information
getPyramidAgeDist

Get the age distribution for the pedigree
getVersion

Get the version number of nprcgenekeepr
getProbandPedigree

Reduce a pedigree to probands and their ancestors
getRequiredCols

Get required column names for a studbook
getSpeciesGestation

Look up the maximum gestation period (days) for one or more species
getPyramidPlot

Create an age-sex pyramid plot of a pedigree
getSpeciesMinBreedingAge

Look up the minimum breeding age (years) for one or more species and sexes
getPotentialSires

List potential sires
getTokenList

Get tokens from a character vector of lines
headerDisplayNames

Convert internal column names to display or header names
kinMatrix2LongForm

Reformat a kinship matrix into long form
hasGenotype

Check for genotype data in dataframe
get_and_or_list

Join a character vector into an and/or list
hasBothParents

Check whether an animal has both parents
groupAddAssign

Add animals to a breeding group or form new groups
is_valid_date_str

Test whether a string is a valid date
isFounder

Identify the founders in a pedigree
get_elapsed_time_str

Format the elapsed time since a start time
gvaConvergence

Recommend gene-drop iterations for a pedigree
kinshipMatrixToKValues

Extract a kValue table from a kinship matrix
kinshipMatricesToKValues

Build a kValue table from a list of kinship matrices
logModuleEvent

Log module events
makeExamplePedigreeFile

Write copy of nprcgenekeepr::examplePedigree into a file
kinship

Generate a kinship matrix
makeCEPH

Make a CEPH-style pedigree for each id
lacy1989Ped

Small hypothetical pedigree (Lacy 1989)
loadSpeciesOverrides

Load user-configurable species reproductive-parameter overrides
loadSiteConfig

Load the site configuration for the modular Shiny application
lacy1989PedAlleles

Gene-drop alleles for lacy1989Ped (5000 iterations)
makeSimPed

Make a simulated pedigree from representative sires and dams
makeGrpNum

Deprecated alias for makeGroupNum
makeGroupMembers

Make the initial groupMembers animal list
makeFounderStatsTable

Create Founder Statistics HTML Table
makePedigreeDiagramData

Convert a pedigree data frame into visNetwork-ready diagram data
makeGroupNum

Make the initial grpNum list
makeGeneticSummaryTable

Create Genetic Summary Statistics HTML Table
makeGeneticDiversityHeatmap

Make a genetic diversity heat map
makeRelationClassesTable

Make a relation classes table from kinship pairs
makePedigreeMatingLayout

Combine the mating-unit forest into visNetwork-ready diagram data
markerExpectedHeterozygosity

Compute per-locus and population-wide expected heterozygosity
mapIdsToObfuscated

Map IDs to Obfuscated IDs
markerKinship

Estimate pairwise kinship directly from marker genotypes (KING-robust)
markerFst

Compute a between-center allele-frequency differentiation statistic (Fst)
markerRealizedRelatednessVariance

Estimate the variance of realized relatedness around pedigree kinship
meanKinship

Calculate mean kinship for each animal in a kinship matrix
markerParentageExclusion

Flag Mendelian-inconsistent recorded parents from marker genotypes
markerParentageLikelihood

Rank candidate replacement parents by a multilocus likelihood (LOD) score
markerObservedHeterozygosity

Compute per-animal observed heterozygosity from marker genotypes
markerLdBlock

Compute a descriptive, same-chromosome pairwise LD/block statistic
mhcHaplotypeFrequency

Summarize MHC haplotype frequencies and flag rare haplotypes
modGeneticDiversityUI

Genetic Diversity Module - UI Function
modCrossCenterIdentityServer

Cross-Center Identity Mapping Module - Server Function
modBreedingGroupsServer

Breeding Groups Module - Server Function
modDeidentifiedExportUI

De-Identified Export Module - UI Function
mhcHaplotypeCarriers

List the animals carrying each MHC haplotype
modBreedingGroupsUI

Breeding Groups Module - UI Function
modDeidentifiedExportServer

De-Identified Export Module - Server Function
modCrossCenterIdentityUI

Cross-Center Identity Mapping Module - UI Function
modGeneticDiversityServer

Genetic Diversity Module - Server Function
modGvAndBgDescServer

Genetic Value and Breeding Group Description Module - Server Function
modMarkerGeneticsServer

Marker Genetics Module - Server Function
modMatePairServer

Mate Pair Analysis Module - Server Function
modGeneticValueUI

Genetic Value Analysis Module - UI Function
modGeneticValueServer

Genetic Value Analysis Module - Server Function
modMatePairUI

Mate Pair Analysis Module - UI Function
modGvAndBgDescUI

Genetic Value and Breeding Group Description Module - UI Function
modInputServer

Data Input and Quality Control Module - Server Function
modInputUI

Data Input and Quality Control Module - UI Function
modMarkerGeneticsUI

Marker Genetics Module - UI Function
modPotentialParentsServer

Potential Parents Module - Server Function
modPedigreeUI

Pedigree Browser Module - UI Function
modORIPReportingUI

ORIP Reporting Module - UI Function
modPotentialParentsUI

Potential Parents Module - UI Function
modSnapshotTrendsServer

Genetic-Health Trends Module - Server Function
modPyramidUI

Age-Sex Pyramid Module - UI Function
modORIPReportingServer

ORIP Reporting Module - Server Function
modPedigreeServer

Pedigree Browser Module - Server Function
modSnapshotTrendsUI

Genetic-Health Trends Module - UI Function
modPyramidServer

Age-Sex Pyramid Module - Server Function
obfuscateGenomicROH

De-identify a computeGenomicROH() result table
modSummaryStatsUI

Summary Statistics Module - UI Function
obfuscateLdBlocks

De-identify a markerLdBlock() result table
obfuscateId

Create ID aliases of a specified length
nprcgenekeepr-package

nprcgenekeepr: Genetic Tools for Colony Management
modSummaryStatsServer

Summary Statistics Module - Server Function
obfuscateGenotypeMatrix

De-identify a sequence-scale genotype matrix
obfuscateDate

Obfuscate dates with a random day offset
obfuscatePed

Obfuscate a pedigree by aliasing IDs and shifting dates
obfuscateMhcHaplotypes

De-identify an MHC haplotype carrier table
ped1Alleles

Gene-drop alleles example (baboon pedigree)
offspringCounts

Tabulate offspring counts, optionally by population
obfuscateTwinRelations

De-identify a twin/zygosity relations table
pedInvalidDates

Example studbook with invalid birth dates
pedOne

Raw pedigree-file fragment for testing (5 columns)
pedFemaleSireMaleDam

Example studbook with sex-mismatched parents
pedMissingBirth

Example studbook missing the birth date column
pedDuplicateIds

Example studbook with a duplicated record
pedGood

Valid example studbook (no QC errors)
pedSameMaleIsSireAndDam

Example studbook with a male as both sire and dam
processQcStudbookResult

Process qcStudbook Result into UI-Friendly Format
plotSnapshotTrends

Plot colony genetic-health trends from a snapshot history
previewBackfillSupport

Count what each date of a rebuilt series rests on, before building it
print.summary.nprcgenekeeprErr

Print an nprcgenekeepr summary object
pedWithGenotypeReport

Genetic-value report for pedWithGenotype
qcPed

Example quality-controlled baboon pedigree
pedWithGenotype

Pedigree with simulated genotypes (from qcPed)
qcPedGvReport

Genetic-value report for qcPed
removeAutoGenIds

Remove automatically generated IDs from pedigree
removeDuplicates

Remove duplicate records from pedigree
removePotentialSires

Remove potential sires from a list of IDs
qcBreeders

Potential breeder IDs (29 baboons)
pedSix

Raw pedigree-file fragment for testing (7 columns)
rankSubjects

Rank animals by genetic value
readAncestryRules

Read an ancestry compatibility rules table from a file
readKinshipOverrides

Read a kinship overrides table from a file
qcStudbook

Run quality control on a studbook or pedigree
removeEarlyDates

Remove dates before a specified year
reportAncestryViolations

Report ancestry-rule violations within formed groups
reportMatePairs

Report eligible individual mate pairs with kinship and genetic-value context
removeUnknownAnimals

Remove placeholder animals added for unknown parents
resolveCrossCenterIds

Merge two centers' pedigrees via a curator-confirmed identity link
reportGV

Generate a genetic value report for a pedigree
runModularApp

Run the Modular Version of GeneKeepR (Deprecated)
runGeneKeepR

Run the GeneKeepR Shiny Application
readTwinRelations

Read a twin/zygosity relations table from a file
readSnapshotHistory

Read a colony snapshot-history table from a file
removeUninformativeFounders

Remove uninformative founders
rhesusGenotypes

Rhesus genotypes (two haplotypes per animal)
rhesusPedigree

Obfuscated rhesus pedigree object
setAutoIdFormat

Set the auto-generated unknown-ID format
safeExecute

Execute an expression with error handling
runQcStudbook

Run Quality Control on Studbook with UI-Friendly Results
set_seed

Set a reproducible RNG seed across R versions
shouldShowChangedColsTab

Determine if Changed Columns tab should be displayed
setExit

Set the exit date when no exit column exists
saveDataframesAsFiles

Write copy of dataframes to either CSV, TXT, or Excel file
savePlotToFile

Save Plot to File
shrinkPedigree

Shrink a pedigree to fit within a bit-size budget
setPopulation

Flag animals as the population of interest
setLabKeyDefaults

Configure Rlabkey authentication for the current session
shouldShowOripTab

Determine if the ORIP Reporting tab should be displayed
toCharacter

Force dataframe columns to character
trimPedigree

Trim a pedigree to a group's ancestors
summary.nprcgenekeeprErr

Summarize a studbook quality-control error list
smallPedTree

Pedigree tree built from smallPed
smallPed

Hypothetical 17-animal pedigree
summarizeKinshipValues

Summarize simulated kinship values
speciesGestation

Per-species reproductive parameters
withinIntegerRange

Get integer within a range
alleleFreq

Count each allele in a vector
addGenotype

Add genotype data to pedigree file
addSexAndAgeToGroup

Build a group data frame with ID, sex, and age
addUIds

Add placeholder IDs for unknown parents
addAnimalsWithNoRelative

Add an NA value for animals with no relative
addParents

Add parents
appUI

Main Application UI for nprcgenekeepr
appServer

Main Application Server for nprcgenekeepr
addBackSecondParents

Add back second parents to a trimmed pedigree
addIdRecords

Add ego records with NA parent IDs