Skip to content

Instantly share code, notes, and snippets.

@zkamvar
Last active April 10, 2021 19:40
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save zkamvar/22ba1cd7649d8d91da18 to your computer and use it in GitHub Desktop.
Function for subsetting loci in a genind object by name
#' Subset loci in a genind object by name
#'
#' @param dat a genind object
#' @param ... names of the loci in character format OR numeric indices of the loci.
#'
#' @return the appropriate names to use for subsetting in a genind object
#' @examples
#' library(adegenet)
#' data(nancycats)
#' # Old way:
#' locNames(nancycats)
#' nancycats[loc = c("L1", "L4")]
#' # New way. Don't have to look up names.
#' nancycats[loc = subLoc(nancycats, "fca8", "fca45")]
#' nancycats[loc = subLoc(nancycats, 1, 4)]
#'
#' data(microbov)
#' microbov[loc = "L1"] # Error :(
#' microbov[loc = "L01"] # The right way
#' microbov[loc = subLoc(microbov, 1)] # The best way
#==============================================================================#
# INSTALLATION: devtools::source_gist("22ba1cd7649d8d91da18")
#==============================================================================#
subLoc <- function(dat, ...){
theLoci <- c(...)
if (is.numeric(theLoci)){
theLoci[theLoci > nLoc(dat)] <- 0
resLoci <- names(locNames(dat))[theLoci]
} else {
resLoci <- names(locNames(dat))[locNames(dat) %in% theLoci]
}
return(resLoci)
}
@zkamvar
Copy link
Author

zkamvar commented Feb 13, 2015

Installation:

devtools::source_gist("22ba1cd7649d8d91da18")

@zkamvar
Copy link
Author

zkamvar commented Apr 25, 2015

Note: For adegenet 2.0, this function is no longer needed.

@Farhad63
Copy link

Farhad63 commented Apr 9, 2020

Hi
What if I wanted to select a subset of SNPs based on a list of their name or a characteristic of SNPS in decadent. For example sub-setting the data based on outlier SNPs. I appreciate your help.

@zkamvar
Copy link
Author

zkamvar commented Apr 9, 2020

Hello,

You shouldn't need this five-year-old function to perform that task. If you have a genind object, you should use something like

myData[loc = c("snp1", "snp2")]

if you have a genlight object, then subsetting is the same as a matrix:

myData[, c("snp1", "snp2")]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment