Jeni
Jeni

Reputation: 958

Transform genomic regions to genomic positions in an R dataframe or GenomicRanges object

I have a dataframe with some genomic intervals and its corresponding coverage in several samples:

       sample1   sample2   sample3
1:1-3    30        NA         NA
1:1-4    NA        40         35
1:4-5    35        NA         NA
1:5-7    NA        50         50
1:6-7    60        NA         NA 

I would like to obtain the same dataframe but for genomic positions:

       sample1    sample2     sample3
1:1      30         40          35
1:2      30         40          35
1:3      30         40          35
1:4      35         40          35
1:5      35         50          50
1:6      60         50          50
1:7      60         50          50

Do you know how can I get this? (I have also tried to transform the dataframe in a GenomicRanges object, but I still don't know how to do this)

Upvotes: 0

Views: 65

Answers (1)

StupidWolf
StupidWolf

Reputation: 46898

Your data which i read in:

tab = structure(list(sample1 = c(30L, NA, 35L, NA, 60L), sample2 = c(NA, 
40L, NA, 50L, NA), sample3 = c(NA, 35L, NA, 50L, NA)), class = "data.frame", row.names = c("1:1-3", 
"1:1-4", "1:4-5", "1:5-7", "1:6-7"))

It depends on how large your dataset is, so this is a GenomicRange based solution:

library(GenomicRanges)
gr = GRanges(rownames(tab))
seq_range = range(gr)
W = width(seq_range)

COV = lapply(tab,function(i){
  i[is.na(i)] = 0
  coverage(gr,weight=i,width=W)
})

cov_samples = sapply(COV,function(i)as.matrix(i[seq_range]))
cov_samples
         sample1 sample2 sample3
[1,]      30      40      35
[2,]      30      40      35
[3,]      30      40      35
[4,]      35      40      35
[5,]      35      50      50
[6,]      60      50      50
[7,]      60      50      50

Now we combine it with the coordinates:

final = data.frame(
seqnames=rep(as.character(seqnames(seq_range)),W),
pos =  unlist(lapply(W,seq,from=1)),
cov_samples)

  seqnames pos sample1 sample2 sample3
1        1   1      30      40      35
2        1   2      30      40      35
3        1   3      30      40      35
4        1   4      35      40      35
5        1   5      35      50      50
6        1   6      60      50      50
7        1   7      60      50      50

Upvotes: 1

Related Questions