How To Write Data In A Granges Object To A Bed File.

Given a GRanges object:

gr <- GRanges(seqnames = Rle(c("chr1", "chr2", "chr1", "chr3"), c(1, 3, 2, 4)),
  ranges = IRanges(1:10, end = 7:16, names = head(letters, 10)),
  strand = Rle(strand(c("-", "+", "*", "+", "-")), c(1, 2, 2, 3, 2)))

You can simply:

df <- data.frame(seqnames=seqnames(gr),
  starts=start(gr)-1,
  ends=end(gr),
  names=c(rep(".", length(gr))),
  scores=c(rep(".", length(gr))),
  strands=strand(gr))

write.table(df, file="foo.bed", quote=F, sep="t", row.names=F, col.names=F)

to write that to foo.bed. The only trick is remembering the BED uses 0-based coordinates. If you have a GRangesList rather than a GRanges object, just use unlist(gr) in place of gr (things should still be in the same order).

Read more here: Source link