### Constructing and Converting GPos Objects Source: https://context7.com/bioconductor/genomicranges/llms.txt Illustrates the creation of memory-efficient GPos objects for single-nucleotide positions. Includes examples of converting between GPos and GRanges classes. ```r library(GenomicRanges) gpos <- GPos( seqnames = c("chr1", "chr1", "chr2", "chr2"), pos = c(100, 200, 150, 300), strand = c("+", "+", "-", "*"), score = c(0.8, 0.9, 0.7, 0.85) ) gr_from_gpos <- as(gpos, "GRanges") gr_width1 <- GRanges("chr1", IRanges(c(10, 20, 30), width = 1)) gpos_from_gr <- as(gr_width1, "GPos") ``` -------------------------------- ### resize Source: https://context7.com/bioconductor/genomicranges/llms.txt Changes the width of ranges while anchoring at the start, end, or center. ```APIDOC ## POST /resize ### Description Adjusts the width of genomic ranges while maintaining a fixed anchor point. ### Method POST ### Endpoint /resize ### Parameters #### Request Body - **gr** (GRanges) - Required - The input ranges. - **width** (integer) - Required - The target width. - **fix** (string) - Required - The anchor point: 'start', 'end', or 'center'. ### Request Example { "gr": "GRanges object", "width": 100, "fix": "start" } ### Response #### Success Response (200) - **resized_gr** (GRanges) - The modified ranges. ``` -------------------------------- ### Generate Promoter and Terminator Regions Source: https://context7.com/bioconductor/genomicranges/llms.txt Calculates promoter and terminator regions relative to transcript start and end sites. These functions allow for custom upstream and downstream offsets and support variable per-range values. ```r library(GenomicRanges) transcripts <- GRanges( seqnames = c("chr1", "chr1", "chr2"), ranges = IRanges(c(10000, 50000, 30000), c(12000, 55000, 35000)), strand = c("+", "-", "+"), tx_id = c("tx1", "tx2", "tx3") ) prom <- promoters(transcripts) prom_custom <- promoters(transcripts, upstream = 1000, downstream = 100) term <- terminators(transcripts) term_custom <- terminators(transcripts, upstream = 500, downstream = 500) prom_variable <- promoters( transcripts, upstream = c(2000, 1500, 2500), downstream = c(200, 100, 300) ) ``` -------------------------------- ### Resize Genomic Ranges Source: https://context7.com/bioconductor/genomicranges/llms.txt The resize function adjusts the width of ranges while maintaining a specific anchor point (start, end, or center). It respects strand orientation by default. ```r library(GenomicRanges) gr <- GRanges(seqnames = c("chr1", "chr1", "chr2"), ranges = IRanges(c(100, 200, 300), width = 50), strand = c("+", "-", "*")) resized_start <- resize(gr, width = 100, fix = "start") resized_center <- resize(gr, width = 100, fix = "center") tss <- resize(gr, width = 1, fix = "start") ``` -------------------------------- ### Constructing GRanges Objects Source: https://context7.com/bioconductor/genomicranges/llms.txt Demonstrates how to initialize a GRanges object using sequence names, IRanges, and metadata columns. It also shows how to define sequence lengths and create objects from simple character strings. ```r library(GenomicRanges) gr <- GRanges( seqnames = Rle(c("chr1", "chr2", "chr1", "chr3"), c(1, 3, 2, 4)), ranges = IRanges(101:110, end = 111:120, names = head(letters, 10)), strand = Rle(strand(c("-", "+", "*", "+", "-")), c(1, 2, 2, 3, 2)), score = 1:10, GC = seq(1, 0, length = 10) ) seqlengths(gr) <- c(249250621, 243199373, 198022430) gr_simple <- GRanges(c("chr1:100-200:+", "chr2:150-250:-")) ``` -------------------------------- ### GRanges Creation and Manipulation Source: https://context7.com/bioconductor/genomicranges/llms.txt Demonstrates how to create GRanges objects from data frames, including handling extra columns and 0-based coordinates. ```APIDOC ## Creating GRanges from DataFrame ### Description Converts a data frame into a GRanges object, optionally keeping extra columns as metadata. ### Method `makeGRangesFromDataFrame()` ### Parameters #### Request Body - **df** (DataFrame) - The input data frame. - **keep.extra.columns** (Logical) - TRUE to keep extra columns as metadata, FALSE otherwise. - **seqnames.field** (String) - Name of the column for sequence names. - **start.field** (String) - Name of the column for start positions. - **end.field** (String) - Name of the column for end positions. - **strand.field** (String) - Name of the column for strand information. - **starts.in.df.are.0based** (Logical) - TRUE if start positions in df are 0-based, FALSE otherwise. ### Request Example ```R # Example with extra columns gr <- makeGRangesFromDataFrame( df, keep.extra.columns = TRUE, seqnames.field = "chromosome", start.field = "start", end.field = "end", strand.field = "strand" ) # Example with 0-based coordinates (BED format) bed_df <- data.frame( chrom = c("chr1", "chr2"), chromStart = c(99, 199), # 0-based chromEnd = c(200, 350) ) gr_from_bed <- makeGRangesFromDataFrame( bed_df, seqnames.field = "chrom", start.field = "chromStart", end.field = "chromEnd", starts.in.df.are.0based = TRUE # Convert 0-based to 1-based ) ``` ### Response #### Success Response (GRanges Object) Returns a GRanges object with ranges and metadata columns as specified. ``` -------------------------------- ### GRanges Constructor Source: https://context7.com/bioconductor/genomicranges/llms.txt Demonstrates how to create GRanges objects, which represent collections of genomic ranges with optional metadata. ```APIDOC ## GRanges Constructor ### Description The GRanges constructor creates a GRanges object representing a collection of genomic ranges with chromosome, start/end positions, strand, and optional metadata columns. ### Method Constructor ### Endpoint N/A (R function) ### Parameters N/A (R function arguments) ### Request Example ```r library(GenomicRanges) # Create a GRanges object with genomic coordinates and metadata gr <- GRanges( seqnames = Rle(c("chr1", "chr2", "chr1", "chr3"), c(1, 3, 2, 4)), ranges = IRanges(101:110, end = 111:120, names = head(letters, 10)), strand = Rle(strand(c("-", "+", "*", "+", "-")), c(1, 2, 2, 3, 2)), score = 1:10, GC = seq(1, 0, length = 10) ) # Set sequence lengths for the genome seqlengths(gr) <- c(249250621, 243199373, 198022430) # Simple creation from character strings gr_simple <- GRanges(c("chr1:100-200:+", "chr2:150-250:-")) ``` ### Response #### Success Response (Object Creation) - **GRanges object**: An object of class GRanges containing the specified genomic ranges and metadata. #### Response Example ``` GRanges object with 10 ranges and 2 metadata columns: seqnames ranges strand | score GC | a chr1 101-111 - | 1 1 b chr2 102-112 + | 2 0.89 c chr2 103-113 + | 3 0.78 ... ``` ``` -------------------------------- ### GPos Constructor Source: https://context7.com/bioconductor/genomicranges/llms.txt Illustrates the creation of GPos objects, a specialized container for genomic positions (single-nucleotide locations). ```APIDOC ## GPos Constructor ### Description The GPos constructor creates a memory-efficient container for storing genomic positions (single-nucleotide locations), useful for SNP positions or methylation sites. ### Method Constructor ### Endpoint N/A (R function) ### Parameters N/A (R function arguments) ### Request Example ```r library(GenomicRanges) # Create GPos object for genomic positions gpos <- GPos( seqnames = c("chr1", "chr1", "chr2", "chr2"), pos = c(100, 200, 150, 300), strand = c("+", "+", "-", "*"), score = c(0.8, 0.9, 0.7, 0.85) ) # Convert GPos to GRanges gr_from_gpos <- as(gpos, "GRanges") # Create GPos from GRanges (ranges must have width 1) gr_width1 <- GRanges("chr1", IRanges(c(10, 20, 30), width = 1)) gpos_from_gr <- as(gr_width1, "GPos") ``` ### Response #### Success Response (Object Creation) - **GPos object**: An object of class GPos containing the specified genomic positions and metadata. #### Response Example ``` StitchedGPos object with 4 positions and 1 metadata column: seqnames pos strand | score | [1] chr1 100 + | 0.8 [2] chr1 200 + | 0.9 [3] chr2 150 - | 0.7 [4] chr2 300 * | 0.85 ``` ``` -------------------------------- ### GRangesList Constructor Source: https://context7.com/bioconductor/genomicranges/llms.txt Explains how to use the GRangesList constructor to create grouped collections of GRanges objects, suitable for features like transcripts. ```APIDOC ## GRangesList Constructor ### Description The GRangesList constructor creates grouped collections of GRanges objects, ideal for representing compound genomic features like transcripts with multiple exons. ### Method Constructor ### Endpoint N/A (R function) ### Parameters N/A (R function arguments) ### Request Example ```r library(GenomicRanges) # Create individual GRanges for exons exons_tx1 <- GRanges( seqnames = "chr2", ranges = IRanges(c(103, 200, 300), c(106, 250, 350)), strand = "+", exon_id = 1:3 ) exons_tx2 <- GRanges( seqnames = c("chr1", "chr1"), ranges = IRanges(c(107, 113), width = 3), strand = c("+", "+"), exon_id = 1:2 ) # Create GRangesList representing transcripts grl <- GRangesList("transcript_A" = exons_tx1, "transcript_B" = exons_tx2) # Access element counts per list element elementNROWS(grl) # Unlist to get a single GRanges unlist(grl, use.names = FALSE) ``` ### Response #### Success Response (Object Creation) - **GRangesList object**: An object of class GRangesList containing grouped GRanges objects. #### Response Example ``` GRangesList object of length 2: $ transcript_A GRanges object with 3 ranges and 1 metadata column: seqnames ranges strand | exon_id [1] chr2 103-106 + | 1 [2] chr2 200-250 + | 2 [3] chr2 300-350 + | 3 $transcript_B GRanges object with 2 ranges and 1 metadata column: seqnames ranges strand | exon_id [1] chr1 107-109 + | 1 [2] chr1 113-115 + | 2 ``` ``` -------------------------------- ### Tile Genome into Bins Source: https://context7.com/bioconductor/genomicranges/llms.txt Demonstrates the use of tileGenome to partition genome sequences into specified numbers of tiles or tiles of fixed width, useful for genome-wide binning. ```R library(GenomicRanges) genome_lengths <- c(chr1 = 249250621, chr2 = 243199373, chr3 = 198022430) tiles_by_n <- tileGenome(genome_lengths, ntile = 1000) tiles_by_width <- tileGenome(genome_lengths, tilewidth = 1000000) ``` -------------------------------- ### Constructing GRangesList Objects Source: https://context7.com/bioconductor/genomicranges/llms.txt Shows how to group multiple GRanges objects into a GRangesList, which is useful for representing transcripts or other compound features. Includes methods for accessing element counts and flattening the list. ```r library(GenomicRanges) exons_tx1 <- GRanges( seqnames = "chr2", ranges = IRanges(c(103, 200, 300), c(106, 250, 350)), strand = "+", exon_id = 1:3 ) exons_tx2 <- GRanges( seqnames = c("chr1", "chr1"), ranges = IRanges(c(107, 113), width = 3), strand = c("+", "+"), exon_id = 1:2 ) grl <- GRangesList("transcript_A" = exons_tx1, "transcript_B" = exons_tx2) elementNROWS(grl) unlist(grl, use.names = FALSE) ``` -------------------------------- ### Access GRanges Components with Accessor Functions Source: https://context7.com/bioconductor/genomicranges/llms.txt Demonstrates the use of essential accessor functions to retrieve and modify components of GRanges and GRangesList objects. These functions allow granular control over genomic interval data, including sequence names, ranges, strands, metadata, and sequence information. ```r library(GenomicRanges) # Create sample GRanges gr <- GRanges( seqnames = c("chr1", "chr2", "chr1"), ranges = IRanges(c(100, 200, 300), c(150, 250, 400)), strand = c("+", "-", "*"), score = c(10, 20, 30), name = c("peak1", "peak2", "peak3") ) seqlengths(gr) <- c(chr1 = 1000, chr2 = 800) # Sequence/chromosome names seqnames(gr) # Rle factor: chr1, chr2, chr1 # Ranges (IRanges object) ranges(gr) # IRanges: 100-150, 200-250, 300-400 # Strand information strand(gr) # Rle factor: +, -, * # Individual coordinate components start(gr) # c(100, 200, 300) end(gr) # c(150, 250, 400) width(gr) # c(51, 51, 101) # Metadata columns (annotations) mcols(gr) # DataFrame with score and name mcols(gr)$score # c(10, 20, 30) gr$name # c("peak1", "peak2", "peak3") - shortcut # Sequence information seqinfo(gr) # Seqinfo object seqlevels(gr) # c("chr1", "chr2") seqlengths(gr) # c(chr1=1000, chr2=800) seqlevelsInUse(gr) # Seqlevels actually present in data # Names of ranges names(gr) # NULL or character vector names(gr) <- c("a", "b", "c") # Length (number of ranges) length(gr) # 3 # Get GRanges without metadata granges(gr) # GRanges with just coordinates # Modify components start(gr) <- c(90, 190, 290) strand(gr) <- c("-", "+", "*") mcols(gr)$new_col <- c("A", "B", "C") ``` -------------------------------- ### Converting DataFrames to GRanges Source: https://context7.com/bioconductor/genomicranges/llms.txt Demonstrates the use of makeGRangesFromDataFrame to automatically convert standard data frames into GRanges objects by detecting genomic coordinate columns. ```r library(GenomicRanges) df <- data.frame( chromosome = c("chr1", "chr1", "chr2", "chr3"), start = c(100, 500, 200, 1000), end = c(200, 600, 350, 1500), strand = c("+", "-", "+", "*"), gene_id = c("gene1", "gene2", "gene3", "gene4"), expression = c(10.5, 25.3, 8.9, 15.2) ) gr <- makeGRangesFromDataFrame(df, keep.extra.columns = TRUE) ``` -------------------------------- ### Perform Genomic Range Queries and Distance Calculations Source: https://context7.com/bioconductor/genomicranges/llms.txt Demonstrates how to find nearest, preceding, and following ranges, as well as calculating distances between GRanges objects. These functions are critical for spatial analysis of genomic features. ```R library(GenomicRanges) query <- GRanges(seqnames = c("chr1", "chr1", "chr1"), ranges = IRanges(c(100, 300, 600), width = 10), strand = c("+", "+", "-")) subject <- GRanges(seqnames = c("chr1", "chr1", "chr1", "chr1"), ranges = IRanges(c(50, 200, 400, 700), width = 20), strand = c("+", "+", "+", "-")) nearest_idx <- nearest(query, subject) nearest_all <- nearest(query, subject, select = "all") precede_idx <- precede(query, subject) follow_idx <- follow(query, subject) dtn <- distanceToNearest(query, subject) dist <- distance(query, subject[1:3]) knn <- nearestKNeighbors(query, subject, k = 2) self_nearest <- nearest(query) ``` -------------------------------- ### Create Genomic Tiling GRanges Objects Source: https://context7.com/bioconductor/genomicranges/llms.txt Generates GRanges objects representing tiled genomic regions. It allows specifying tile width and whether to cut the last tile in a chromosome, ensuring tiles do not span chromosome boundaries. Useful for creating bins for coverage analysis or other genomic segmentation tasks. ```r library(GenomicRanges) # Define genome lengths genome_lengths <- c(chr1 = 10000000, chr2 = 8000000) # Cut tiles at chromosome boundaries tiles_cut <- tileGenome(genome_lengths, tilewidth = 1000000, cut.last.tile.in.chrom = TRUE) # Returns GRanges (not GRangesList) # Tiles don't span chromosomes, last tile may be smaller # Example: Create 10kb bins for coverage analysis bins_10kb <- tileGenome(genome_lengths, tilewidth = 10000, cut.last.tile.in.chrom = TRUE) # Use with Seqinfo object si <- Seqinfo(seqnames = names(genome_lengths), seqlengths = genome_lengths) tiles_from_seqinfo <- tileGenome(si, tilewidth = 500000, cut.last.tile.in.chrom = TRUE) ``` -------------------------------- ### makeGRangesFromDataFrame Function Source: https://context7.com/bioconductor/genomicranges/llms.txt Details on using makeGRangesFromDataFrame to convert data frames into GRanges objects. ```APIDOC ## makeGRangesFromDataFrame ### Description The makeGRangesFromDataFrame function converts a data.frame or DataFrame to a GRanges object by automatically detecting coordinate columns. ### Method Function ### Endpoint N/A (R function) ### Parameters N/A (R function arguments) ### Request Example ```r library(GenomicRanges) # Create a data frame with genomic coordinates df <- data.frame( chromosome = c("chr1", "chr1", "chr2", "chr3"), start = c(100, 500, 200, 1000), end = c(200, 600, 350, 1500), strand = c("+", "-", "+", "*"), gene_id = c("gene1", "gene2", "gene3", "gene4"), expression = c(10.5, 25.3, 8.9, 15.2) ) # Convert the data frame to a GRanges object gr_from_df <- makeGRangesFromDataFrame(df, keep.extra.columns=TRUE) # Output: # GRanges object with 4 ranges and 2 metadata columns: # seqnames ranges strand | gene_id expression # [1] chr1 100-200 + | gene1 10.5 # [2] chr1 500-600 - | gene2 25.3 # [3] chr2 200-350 + | gene3 8.9 # [4] chr3 1000-1500 * | gene4 15.2 ``` ### Response #### Success Response (Object Creation) - **GRanges object**: A GRanges object created from the input data frame. #### Response Example ``` GRanges object with 4 ranges and 2 metadata columns: seqnames ranges strand | gene_id expression [1] chr1 100-200 + | gene1 10.5 [2] chr1 500-600 - | gene2 25.3 [3] chr2 200-350 + | gene3 8.9 [4] chr3 1000-1500 * | gene4 15.2 ``` ``` -------------------------------- ### coverage Source: https://context7.com/bioconductor/genomicranges/llms.txt Computes the degree of overlap (coverage depth) at each position across all ranges. ```APIDOC ## POST /coverage ### Description Calculates the coverage depth for genomic ranges, returning an RleList object. ### Method POST ### Endpoint /coverage ### Parameters #### Request Body - **reads** (GRanges) - Required - The input ranges to calculate coverage for. - **weight** (numeric/character) - Optional - Weighting factor for coverage calculation. - **shift** (integer) - Optional - Number of positions to shift the ranges. ### Request Example { "reads": "GRanges object", "weight": "quality" } ### Response #### Success Response (200) - **coverage** (RleList) - The calculated coverage depth per chromosome. ``` -------------------------------- ### shift Source: https://context7.com/bioconductor/genomicranges/llms.txt Moves all ranges by a specified number of base pairs. ```APIDOC ## shift ### Description The shift function moves all ranges by a specified number of base pairs. It supports positive values for right shifts and negative values for left shifts. ### Method Function Call ### Parameters #### Arguments - **x** (GRanges) - Required - The input ranges object. - **shift** (integer/vector) - Required - The number of base pairs to shift. Can be a single value or a vector of the same length as the input ranges. ### Request Example shift(gr, shift = 100) ### Response #### Success Response (200) - **result** (GRanges) - The shifted genomic ranges object. ``` -------------------------------- ### flank Source: https://context7.com/bioconductor/genomicranges/llms.txt Returns flanking regions upstream or downstream of the input ranges. ```APIDOC ## POST /flank ### Description Generates flanking regions relative to the start or end of the input ranges, respecting strand orientation. ### Method POST ### Endpoint /flank ### Parameters #### Request Body - **gr** (GRanges) - Required - The input ranges. - **width** (integer) - Required - The width of the flanking region. - **start** (logical) - Required - Whether to anchor at the start. - **both** (logical) - Optional - Whether to return both upstream and downstream regions. ### Request Example { "gr": "GRanges object", "width": 500, "start": true } ### Response #### Success Response (200) - **flanked_gr** (GRanges) - The resulting flanking ranges. ``` -------------------------------- ### reduce Source: https://context7.com/bioconductor/genomicranges/llms.txt Merges overlapping or adjacent ranges into a set of non-overlapping ranges. ```APIDOC ## POST /reduce ### Description Merges overlapping or adjacent ranges within a GRanges object into a set of non-overlapping ranges. ### Method POST ### Endpoint /reduce ### Parameters #### Request Body - **gr** (GRanges) - Required - The input genomic ranges object. - **with.revmap** (logical) - Optional - If TRUE, returns a mapping of original indices to reduced ranges. - **ignore.strand** (logical) - Optional - If TRUE, ignores strand information during merging. - **min.gapwidth** (integer) - Optional - Minimum gap width to allow merging adjacent ranges. ### Request Example { "gr": "GRanges object", "min.gapwidth": 5 } ### Response #### Success Response (200) - **reduced_gr** (GRanges) - The resulting non-overlapping ranges. ``` -------------------------------- ### Perform Genomic Set Operations Source: https://context7.com/bioconductor/genomicranges/llms.txt Covers union, intersection, and set difference operations for GRanges objects. Includes both standard set operations and parallel (element-wise) variants. ```R library(GenomicRanges) peaks_sample1 <- GRanges(seqnames = c("chr1", "chr1", "chr2"), ranges = IRanges(c(100, 500, 200), c(200, 700, 400)), strand = "+") peaks_sample2 <- GRanges(seqnames = c("chr1", "chr1", "chr2"), ranges = IRanges(c(150, 600, 300), c(300, 800, 500)), strand = "+") all_peaks <- union(peaks_sample1, peaks_sample2) shared_peaks <- intersect(peaks_sample1, peaks_sample2) unique_to_sample1 <- setdiff(peaks_sample1, peaks_sample2) gr1 <- GRanges("chr1", IRanges(c(100, 300), c(200, 400))) gr2 <- GRanges("chr1", IRanges(c(150, 350), c(250, 450))) punion_result <- punion(gr1, gr2) pintersect_result <- pintersect(gr1, gr2) psetdiff_result <- psetdiff(gr1, gr2) ``` -------------------------------- ### findOverlaps Source: https://context7.com/bioconductor/genomicranges/llms.txt Identifies overlapping ranges between two GRanges objects. ```APIDOC ## findOverlaps ### Description Identifies overlapping ranges between query and subject GRanges objects, returning a Hits object with paired indices. ### Method `findOverlaps(query, subject, ...)` ### Parameters #### Query Parameters - **query** (GRanges) - The query GRanges object. - **subject** (GRanges) - The subject GRanges object. - **ignore.strand** (Logical) - If TRUE, strand is ignored during overlap detection. - **select** (String) - Specifies which hits to return: "all" (default), "first", "last", "any". - **type** (String) - Type of overlap: "any" (default), "start", "end", "within", "equal". - **minoverlap** (Integer) - Minimum overlap length required. ### Request Example ```R library(GenomicRanges) # Create query ranges query <- GRanges( seqnames = c("chr1", "chr1", "chr2"), ranges = IRanges(c(1, 100, 200), c(50, 200, 300)), strand = c("+", "+", "-") ) # Create subject ranges subject <- GRanges( seqnames = c("chr1", "chr1", "chr2", "chr2"), ranges = IRanges(c(25, 150, 180, 250), c(75, 180, 220, 280)), strand = c("+", "+", "-", "-") ) # Find all overlaps hits <- findOverlaps(query, subject) # Find overlaps ignoring strand hits_no_strand <- findOverlaps(query, subject, ignore.strand = TRUE) # Select only first overlap per query first_hits <- findOverlaps(query, subject, select = "first") # Find overlaps with minimum overlap of 20bp hits_min <- findOverlaps(query, subject, minoverlap = 20) # Different overlap types hits_within <- findOverlaps(query, subject, type = "within") ``` ### Response #### Success Response (Hits Object) Returns a Hits object containing the indices of overlapping ranges. #### Response Example ``` Hits object with 4 hits: queryHits subjectHits 1 1 2 1 2 2 3 3 3 4 ``` ``` -------------------------------- ### Calculate Distance to Nearest Genomic Features Source: https://context7.com/bioconductor/genomicranges/llms.txt Shows how to compute the distance between query ranges and their nearest subject ranges, including extracting metadata and handling overlaps. ```R library(GenomicRanges) snps <- GRanges(seqnames = c("chr1", "chr1", "chr2", "chr2"), ranges = IRanges(c(1000, 5000, 2000, 8000), width = 1), strand = "*", snp_id = paste0("rs", 1:4)) genes <- GRanges(seqnames = c("chr1", "chr1", "chr2", "chr2"), ranges = IRanges(c(800, 4500, 1500, 10000), c(1200, 5500, 2500, 12000)), strand = c("+", "-", "+", "-"), gene = c("GENE1", "GENE2", "GENE3", "GENE4")) dtn <- distanceToNearest(snps, genes) results <- data.frame(snp = snps$snp_id[queryHits(dtn)], nearest_gene = genes$gene[subjectHits(dtn)], distance = mcols(dtn)$distance) ``` -------------------------------- ### Identify Gaps and Disjoin Ranges Source: https://context7.com/bioconductor/genomicranges/llms.txt Finds uncovered regions between ranges using gaps or creates non-overlapping segments from overlapping ranges using disjoin. ```r library(GenomicRanges) gr <- GRanges( seqnames = c("chr1", "chr1", "chr1"), ranges = IRanges(c(100, 300, 600), c(200, 400, 700)), strand = "+" ) seqlengths(gr) <- c(chr1 = 1000) gap_regions <- gaps(gr) gr2 <- GRanges( seqnames = c("chr1", "chr1", "chr1"), ranges = IRanges(c(100, 150, 200), c(200, 250, 300)), strand = "+" ) disjoined <- disjoin(gr2) isDisjoint(gr) ``` -------------------------------- ### gaps and disjoin Source: https://context7.com/bioconductor/genomicranges/llms.txt Finds uncovered regions between ranges or breaks ranges into non-overlapping segments. ```APIDOC ## gaps and disjoin ### Description The gaps function finds uncovered regions between ranges, while disjoin creates non-overlapping ranges representing all distinct regions. ### Method Function Call ### Parameters #### Arguments - **x** (GRanges) - Required - The input ranges object. - **start/end** (integer) - Optional - Custom boundaries for gap calculation. - **with.revmap** (boolean) - Optional - Whether to include mapping back to original ranges. ### Request Example gaps(gr) ### Response #### Success Response (200) - **result** (GRanges) - The resulting gaps or disjointed ranges. ``` -------------------------------- ### narrow and restrict Source: https://context7.com/bioconductor/genomicranges/llms.txt Extracts subranges or limits ranges to specific genomic boundaries. ```APIDOC ## narrow and restrict ### Description The narrow function extracts a subrange from each range by specifying start/end/width within the range. The restrict function limits ranges to specified genomic boundaries. ### Method Function Call ### Parameters #### Arguments - **x** (GRanges) - Required - The input ranges object. - **start/end/width** (integer) - Optional - Coordinates for narrowing or restricting. - **keep.all.ranges** (boolean) - Optional - Whether to keep ranges that fall outside bounds. ### Request Example narrow(gr, start = 10, end = 50) ### Response #### Success Response (200) - **result** (GRanges) - The modified genomic ranges object. ``` -------------------------------- ### Convert Data Frame to GRanges Source: https://context7.com/bioconductor/genomicranges/llms.txt Converts a standard data frame into a GRanges object. It supports specifying column mappings and handling 0-based coordinate systems common in BED files. ```r gr <- makeGRangesFromDataFrame(df, keep.extra.columns = TRUE, seqnames.field = "chromosome", start.field = "start", end.field = "end", strand.field = "strand") bed_df <- data.frame(chrom = c("chr1", "chr2"), chromStart = c(99, 199), chromEnd = c(200, 350)) gr_from_bed <- makeGRangesFromDataFrame(bed_df, seqnames.field = "chrom", start.field = "chromStart", end.field = "chromEnd", starts.in.df.are.0based = TRUE) ``` -------------------------------- ### reduce Source: https://context7.com/bioconductor/genomicranges/llms.txt Merges overlapping and adjacent ranges within a GRanges object. ```APIDOC ## reduce ### Description Merges overlapping and adjacent ranges within a GRanges object to produce a simplified, non-overlapping set. ### Method `reduce(x, ...)` ### Parameters #### Query Parameters - **x** (GRanges) - The input GRanges object. - **min.gapwidth** (Integer) - The minimum gap width between ranges to be considered separate. Ranges closer than this will be merged. - **with.revmap** (Logical) - If TRUE, returns a list with the reduced ranges and a revmap indicating which original range each reduced range came from. - **with.group** (Logical) - If TRUE, returns a list with the reduced ranges and a group vector indicating which group each original range belongs to. ### Request Example ```R library(GenomicRanges) # Create a GRanges object with overlapping and adjacent ranges gr_to_reduce <- GRanges( seqnames = c("chr1", "chr1", "chr1", "chr2", "chr2"), ranges = IRanges(c(10, 50, 100, 20, 80), c(30, 70, 120, 60, 100)), strand = "+" ) # Reduce the ranges reduced_gr <- reduce(gr_to_reduce) # Returns: GRanges object with merged ranges # Reduce with a minimum gap width of 10 reduced_gap <- reduce(gr_to_reduce, min.gapwidth = 10) # Reduce and get the reverse mapping reduced_with_revmap <- reduce(gr_to_reduce, with.revmap = TRUE) # Reduce and get group information reduced_with_group <- reduce(gr_to_reduce, with.group = TRUE) ``` ### Response #### Success Response (GRanges Object or List) Returns a GRanges object with the merged ranges. If `with.revmap` or `with.group` is TRUE, returns a list containing the reduced GRanges and the mapping information. ``` -------------------------------- ### subsetByOverlaps Source: https://context7.com/bioconductor/genomicranges/llms.txt Extracts elements from a query GRanges that overlap with a subject GRanges. ```APIDOC ## subsetByOverlaps ### Description Extracts elements from the query GRanges that overlap with at least one element in the subject GRanges. ### Method `subsetByOverlaps(query, subject, ...)` ### Parameters #### Query Parameters - **query** (GRanges) - The GRanges object to subset. - **subject** (GRanges) - The GRanges object containing regions to check for overlaps. - **invert** (Logical) - If TRUE, returns elements that do NOT overlap. - **ignore.strand** (Logical) - If TRUE, strand is ignored during overlap detection. - **minoverlap** (Integer) - Minimum overlap length required. ### Request Example ```R library(GenomicRanges) # Create query ranges all_features <- GRanges( seqnames = c("chr1", "chr1", "chr2", "chr2", "chr3"), ranges = IRanges(c(100, 500, 200, 800, 300), width = 100), strand = "+", feature_id = paste0("feature", 1:5) ) # Create region of interest region_of_interest <- GRanges( seqnames = c("chr1", "chr2"), ranges = IRanges(c(50, 150), c(300, 400)) ) # Get features that overlap with regions of interest overlapping <- subsetByOverlaps(all_features, region_of_interest) # Invert selection: get features that DON'T overlap non_overlapping <- subsetByOverlaps(all_features, region_of_interest, invert = TRUE) # With minimum overlap requirement overlapping_min <- subsetByOverlaps(all_features, region_of_interest, minoverlap = 50) # Ignore strand overlapping_unstrand <- subsetByOverlaps(all_features, region_of_interest, ignore.strand = TRUE) ``` ### Response #### Success Response (GRanges Object) Returns a GRanges object containing the subset of elements from the query that meet the overlap criteria. ``` -------------------------------- ### Narrow and Restrict Ranges Source: https://context7.com/bioconductor/genomicranges/llms.txt Extracts sub-ranges using narrow or clips ranges to genomic boundaries using restrict and trim. Useful for filtering ranges based on coordinate constraints. ```r library(GenomicRanges) gr <- GRanges( seqnames = c("chr1", "chr1", "chr2"), ranges = IRanges(c(100, 200, 300), c(200, 350, 500)), strand = "+" ) narrowed <- narrow(gr, start = 10, end = 50) seqlengths(gr) <- c(chr1 = 300, chr2 = 400) restricted <- restrict(gr, start = 150, end = 350) trimmed <- trim(gr) ``` -------------------------------- ### Calculate Genomic Coverage Source: https://context7.com/bioconductor/genomicranges/llms.txt The coverage function computes the depth of overlap at each position across ranges. It returns an RleList and supports weighting, shifting, and conversion to GRanges objects. ```r library(GenomicRanges) reads <- GRanges(seqnames = c("chr1", "chr1", "chr1", "chr1", "chr2"), ranges = IRanges(c(1, 5, 10, 8, 20), width = c(10, 8, 12, 6, 15)), strand = "+") seqlengths(reads) <- c(chr1 = 50, chr2 = 50) cov <- coverage(reads) weighted_cov <- coverage(reads, weight = c(30, 25, 35, 28, 32)) shifted_cov <- coverage(reads, shift = 5) high_cov_regions <- slice(cov[["chr1"]], lower = 2) ``` -------------------------------- ### Subset Features by Overlaps Source: https://context7.com/bioconductor/genomicranges/llms.txt Extracts elements from a query that overlap with at least one element in a subject. Supports inversion to find non-overlapping features. ```r overlapping <- subsetByOverlaps(all_features, region_of_interest) non_overlapping <- subsetByOverlaps(all_features, region_of_interest, invert = TRUE) overlapping_min <- subsetByOverlaps(all_features, region_of_interest, minoverlap = 50) overlapping_unstrand <- subsetByOverlaps(all_features, region_of_interest, ignore.strand = TRUE) ``` -------------------------------- ### Find Overlaps Between GRanges Source: https://context7.com/bioconductor/genomicranges/llms.txt Identifies overlapping ranges between query and subject objects. It returns a Hits object and supports various parameters like strand sensitivity, overlap types, and minimum overlap thresholds. ```r hits <- findOverlaps(query, subject) queryHits(hits) subjectHits(hits) hits_no_strand <- findOverlaps(query, subject, ignore.strand = TRUE) first_hits <- findOverlaps(query, subject, select = "first") hits_min <- findOverlaps(query, subject, minoverlap = 20) hits_within <- findOverlaps(query, subject, type = "within") ``` -------------------------------- ### countOverlaps Source: https://context7.com/bioconductor/genomicranges/llms.txt Counts the number of overlaps for each query range with subject ranges. ```APIDOC ## countOverlaps ### Description Counts the number of overlaps for each query range with the subject ranges. ### Method `countOverlaps(query, subject, ...)` ### Parameters #### Query Parameters - **query** (GRanges) - The query GRanges object. - **subject** (GRanges) - The subject GRanges object. - **ignore.strand** (Logical) - If TRUE, strand is ignored during overlap detection. - **minoverlap** (Integer) - Minimum overlap length required. ### Request Example ```R library(GenomicRanges) # Create query ranges (e.g., sequencing reads) reads <- GRanges( seqnames = rep("chr1", 5), ranges = IRanges(c(10, 50, 100, 150, 200), width = 50), strand = "+" ) # Create subject ranges (e.g., gene regions) genes <- GRanges( seqnames = rep("chr1", 3), ranges = IRanges(c(1, 120, 190), c(80, 180, 250)), strand = "+", gene_name = c("geneA", "geneB", "geneC") ) # Count overlaps per read counts <- countOverlaps(reads, genes) # Count overlaps ignoring strand counts_unstrand <- countOverlaps(reads, genes, ignore.strand = TRUE) # Count with minimum overlap requirement counts_min <- countOverlaps(reads, genes, minoverlap = 30) # Self-overlap counting self_counts <- countOverlaps(genes) ``` ### Response #### Success Response (Integer Vector) Returns an integer vector where each element is the count of overlaps for the corresponding query range. ``` -------------------------------- ### Calculate Binned Average with binnedAverage Source: https://context7.com/bioconductor/genomicranges/llms.txt Computes the average of a genomic variable (RleList) over specified bins (GRanges). This function is useful for summarizing signal data, like coverage, within defined genomic intervals. It supports NA handling. ```r library(GenomicRanges) # Create bins (e.g., 1kb windows) seqlengths <- c(chr1 = 10000, chr2 = 8000) bins <- tileGenome(seqlengths, tilewidth = 1000, cut.last.tile.in.chrom = TRUE) # Create a numeric variable along the genome (e.g., coverage) # Simulated coverage as RleList cov <- RleList( chr1 = Rle(c(rep(0, 500), rep(5, 2000), rep(10, 3000), rep(2, 4500))), chr2 = Rle(c(rep(3, 4000), rep(8, 4000))) ) # Calculate binned average bins_with_avg <- binnedAverage(bins, cov, varname = "avg_coverage") # Access results mcols(bins_with_avg)$avg_coverage # Example with NA handling cov_with_na <- RleList( chr1 = Rle(c(rep(NA, 500), rep(5, 2000), rep(10, 7500))), chr2 = Rle(c(rep(3, 4000), rep(NA, 4000))) ) bins_na_rm <- binnedAverage(bins, cov_with_na, varname = "avg_cov", na.rm = TRUE) ``` -------------------------------- ### Generate Flanking Regions Source: https://context7.com/bioconductor/genomicranges/llms.txt The flank function calculates regions upstream or downstream of existing ranges, respecting strand orientation. It is commonly used to define promoters or regulatory regions. ```r library(GenomicRanges) genes <- GRanges(seqnames = c("chr1", "chr1", "chr2"), ranges = IRanges(c(1000, 5000, 3000), c(2000, 6000, 4000)), strand = c("+", "-", "+")) upstream <- flank(genes, width = 500, start = TRUE) downstream <- flank(genes, width = 500, start = FALSE) both_flanks <- flank(genes, width = 500, start = TRUE, both = TRUE) ``` -------------------------------- ### Shift Genomic Ranges Source: https://context7.com/bioconductor/genomicranges/llms.txt Moves genomic ranges by a specified number of base pairs. Supports uniform shifts, variable shifts per range, and strand-specific adjustments. ```r library(GenomicRanges) gr <- GRanges( seqnames = c("chr1", "chr1", "chr2"), ranges = IRanges(c(100, 200, 300), width = 50), strand = c("+", "-", "+") ) shifted_right <- shift(gr, shift = 100) shifted_left <- shift(gr, shift = -50) shifted_var <- shift(gr, shift = c(10, 20, 30)) reads <- GRanges( seqnames = rep("chr1", 4), ranges = IRanges(c(100, 200, 300, 400), width = 50), strand = c("+", "+", "-", "-") ) fragment_shift <- ifelse(strand(reads) == "+", 100, -100) adjusted <- shift(reads, shift = fragment_shift) ``` -------------------------------- ### Count Overlaps per Range Source: https://context7.com/bioconductor/genomicranges/llms.txt Calculates the number of overlaps for each range in a query against a subject. Useful for quantifying sequencing reads over genomic features. ```r counts <- countOverlaps(reads, genes) counts_unstrand <- countOverlaps(reads, genes, ignore.strand = TRUE) counts_min <- countOverlaps(reads, genes, minoverlap = 30) self_counts <- countOverlaps(genes) ```