Convert intervals + values data.frame to an interval-indexed matrix
Source:R/intervals-to-mat.R
gintervals.to_mat.RdBuilds a numeric matrix of value columns whose rows are indexed by
intervals. The intervals are carried in attr(mat, "intervals") as the
authoritative identity; rownames(mat) are display-only (default
"chrom:start-end") and are NEVER parsed back by
gintervals.from_mat. This avoids the round-trip corruption
that occurs when chrom names contain underscores or other separators.
Arguments
- df
data.frame with
chrom,start,endand zero or more value columns. May contain anintervalIDcolumn (fromgextract), which is kept in the attribute but excluded from the matrix.- id_col
optional column name in
dfwhose values become rownames. IfNULL(default), rownames are"chrom:start-end".- value_cols
character vector of column names to use as matrix data. If
NULL(default), auto-detect: all columns exceptchrom,start,end,intervalID. Auto-detect errors if any selected column is non-numeric; passvalue_colsexplicitly to override.- labels
if
TRUE(default), setrownames(mat)to eitherdf[[id_col]](ifid_colis supplied) or"chrom:start-end". IfFALSE, leave rownamesNULL- useful in pipelines that don't need the display labels and would prefer to skip the construction cost on large inputs. WhenFALSE, theid_colargument is ignored.
Value
An intervs_mat object: a numeric matrix subclass with the
intervals attached as attr(., "intervals"). Supports row/column
subsetting ([) and rbind() while preserving the attribute.
Examples
df <- data.frame(
chrom = c("chr1", "chr1", "chr2"),
start = c(100L, 500L, 200L),
end = c(200L, 700L, 400L),
t1 = c(1.5, 2.5, 3.5),
t2 = c(10, 20, 30)
)
mat <- gintervals.to_mat(df)
rownames(mat)
#> [1] "chr1:100-200" "chr1:500-700" "chr2:200-400"
# subset preserves intervals:
sub <- mat[c(1, 3), ]
attr(sub, "intervals")
#> chrom start end
#> 1 chr1 100 200
#> 2 chr2 200 400
# round-trip back to a data.frame:
gintervals.from_mat(sub)
#> chrom start end t1 t2
#> 1 chr1 100 200 1.5 10
#> 2 chr2 200 400 3.5 30