This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to save GRanges object to csv file

Currently this is what I do

library(Homo.sapiens)
l <- genes(TxDb.Hsapiens.UCSC.hg19.knownGene)
> l
GRanges object with 23056 ranges and 1 metadata column:
        seqnames                 ranges strand   |     gene_id
           <Rle>              <IRanges>  <Rle>   | <character>
      1    chr19 [ 58858172,  58874214]      -   |           1
     10     chr8 [ 18248755,  18258723]      +   |          10
    100    chr20 [ 43248163,  43280376]      -   |         100
   1000    chr18 [ 25530930,  25757445]      -   |        1000
  10000     chr1 [243651535, 244006886]      -   |       10000
    ...      ...                    ...    ... ...         ...
   9991     chr9 [114979995, 115095944]      -   |        9991
   9992    chr21 [ 35736323,  35743440]      +   |        9992
   9993    chr22 [ 19023795,  19109967]      -   |        9993
   9994     chr6 [ 90539619,  90584155]      +   |        9994
   9997    chr22 [ 50961997,  50964905]      -   |        9997
  -------
  seqinfo: 93 sequences (1 circular) from hg19 genome

I want to save the list l to a csv file. How can I do that?

export granges

What have you tried?

write.csv(l, file = "MyData.csv")
Error in as.vector(x) : no method for coercing this S4 class to a vector

3 answers

write.table( x = data.frame(l), file = "/path/to/file.csv", sep=",", col.names=TRUE, row.names=FALSE, quote=FALSE )

Probably R is even smart enough so that data.frame() is not required.

I get error Error in as.vector(x) : no method for coercing this S4 class to a vector

You should convert to data frame first:

genes_df = as(genes_gr, "data.frame")

Using standard as.data.frame() or data.frame() can cause issues with GRanges. That may be why write.csv() is failing.

Using R >= 3.3.3 and Bioconductor >= 3.4, the commands that you provided worked on my computer. If you are using older versions, perhaps you can consider upgrading?

> library(Homo.sapiens)
> l <- genes(TxDb.Hsapiens.UCSC.hg19.knownGene)
> write.csv(l, file = "MyData.csv")
> system("head MyData.csv")
"","seqnames","start","end","width","strand","gene_id"
"1","chr19",58858172,58874214,16043,"-","1"
"2","chr8",18248755,18258723,9969,"+","10"
"3","chr20",43248163,43280376,32214,"-","100"
"4","chr18",25530930,25757445,226516,"-","1000"
"5","chr1",243651535,244006886,355352,"-","10000"
"6","chrX",49217763,49233491,15729,"+","100008586"
"7","chr3",101395274,101398057,2784,"+","100009676"
"8","chr14",71050957,71067384,16428,"-","10001"
"9","chr15",72102894,72110597,7704,"+","10002"

Log in to answer this question.