Skip to content

Instantly share code, notes, and snippets.

@mikelove
Created March 17, 2025 13:56
Show Gist options
  • Save mikelove/eaa3ab08dbf786a5d31fdbfc4cb5de78 to your computer and use it in GitHub Desktop.
Save mikelove/eaa3ab08dbf786a5d31fdbfc4cb5de78 to your computer and use it in GitHub Desktop.
Adding metadata to tiles
> x <- data.frame(seqnames="chr1", start=c(1,101), width=100, foo=c("bar","boo")) |> as_granges()
> x
GRanges object with 2 ranges and 1 metadata column:
seqnames ranges strand | foo
<Rle> <IRanges> <Rle> | <character>
[1] chr1 1-100 * | bar
[2] chr1 101-200 * | boo
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
> x |> tile_ranges(25)
GRanges object with 8 ranges and 1 metadata column:
seqnames ranges strand | partition
<Rle> <IRanges> <Rle> | <integer>
[1] chr1 1-25 * | 1
[2] chr1 26-50 * | 1
[3] chr1 51-75 * | 1
[4] chr1 76-100 * | 1
[5] chr1 101-125 * | 2
[6] chr1 126-150 * | 2
[7] chr1 151-175 * | 2
[8] chr1 176-200 * | 2
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
> tiled <- x |> tile_ranges(25)
> x |> mutate(partition = seq_along(foo))
GRanges object with 2 ranges and 2 metadata columns:
seqnames ranges strand | foo partition
<Rle> <IRanges> <Rle> | <character> <integer>
[1] chr1 1-100 * | bar 1
[2] chr1 101-200 * | boo 2
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
> meta <- x |> mutate(partition = seq_along(foo)) |> mcols()
> dplyr::left_join(as_tibble(mcols(tiled)), as_tibble(meta))
Joining with `by = join_by(partition)`
# A tibble: 8 × 2
partition foo
<int> <chr>
1 1 bar
2 1 bar
3 1 bar
4 1 bar
5 2 boo
6 2 boo
7 2 boo
8 2 boo
> mcols(tiled) <- dplyr::left_join(as_tibble(mcols(tiled)), as_tibble(meta))
Joining with `by = join_by(partition)`
> tiled
GRanges object with 8 ranges and 2 metadata columns:
seqnames ranges strand | partition foo
<Rle> <IRanges> <Rle> | <integer> <character>
[1] chr1 1-25 * | 1 bar
[2] chr1 26-50 * | 1 bar
[3] chr1 51-75 * | 1 bar
[4] chr1 76-100 * | 1 bar
[5] chr1 101-125 * | 2 boo
[6] chr1 126-150 * | 2 boo
[7] chr1 151-175 * | 2 boo
[8] chr1 176-200 * | 2 boo
-------
seqinfo: 1 sequence from an unspecified genome; no seqlengths
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment