Question: Unable to perform for loop over list of GRanges
gravatar for neo_noob
8 weeks ago by
neo_noob0 wrote:

Hi All, I am new to bioinformatics and R. I am trying to learn with online tutorials and forums, but could not find anything related to my simple question.

I have a few GRanges defined in R. I wanted to rename the columns of metadata of each of the Granges.

I am using

names(mcols(gr))=c("name1", "name2", "name3")

this works when I try to rename GR individually, but it does not work within a for loop.

for ( gr in c(gr1, gr2, gr3, gr4) ) { names(mcols(gr)) = c("name1", "name2", "name3") }

I got this error:

invalid for() loop sequence

does it mean I can not use for loops for GRs? what am I doing wrong here? what are other ways I can do this?

forum R • 167 views
ADD COMMENTlink modified 8 weeks ago by Papyrus330 • written 8 weeks ago by neo_noob0

Did not test your code but inside the loop you're missing a parenthesis right after gr) to close the names function, and the last double quotes after name3 is a single quote. names(mcols(gr) = c("name1", "name2", "name3') should be names(mcols(gr)) = c("name1", "name2", "name3")

ADD REPLYlink modified 8 weeks ago • written 8 weeks ago by Papyrus330

this was an error while writing here. But my actual was code properly quoted and with parenthesis. And it does not work

ADD REPLYlink written 8 weeks ago by neo_noob0
gravatar for Papyrus
8 weeks ago by
Papyrus330 wrote:

It is possible that there may be specific functions from the GenomicRanges package, but to follow your loop you could do this: the key is to have the GRanges as a "standard" list object and not a GRangesList (assuming the GRanges have the same metadata columns):

 foo <- GRangesList( # Create example GRanges
  GRanges(seqnames = c(1:5), ranges = IRanges(start = 1:5, end = 1:5), m1 = letters[1:5], m2 = letters[1:5], m3 = letters[1:5]),
  GRanges(seqnames = c(5:10), ranges = IRanges(start = 5:10, end = 5:10), m1 = letters[5:10], m2 = letters[5:10], m3 = letters[5:10]),
  GRanges(seqnames = c(10:15), ranges = IRanges(start = 10:15, end = 10:15), m1 = letters[10:15], m2 = letters[10:15], m3 = letters[10:15])

foo.list <- as.list(foo) # Set as list

for(gr in 1:length(foo.list)){ # Loop to change the metadata column names
    names(mcols(foo.list[[gr]])) <- c("name1", "name2", "name3")

foo.list2 <- GRangesList(foo.list) # Go back to GRanges list
ADD COMMENTlink modified 8 weeks ago • written 8 weeks ago by Papyrus330

Yes, this works. Thank you so much!

ADD REPLYlink written 8 weeks ago by neo_noob0
Please log in to add an answer.


Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1712 users visited in the last hour