Unable to perform for loop over list of GRanges
1
0
Entering edit mode
14 months ago
neo_noob • 0

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?

R Forum • 630 views
ADD COMMENT
0
Entering edit mode

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 REPLY
0
Entering edit mode

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

ADD REPLY
2
Entering edit mode
14 months ago
Papyrus ★ 1.1k

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):

library(GenomicRanges)
 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 COMMENT
0
Entering edit mode

Yes, this works. Thank you so much!

ADD REPLY

Login before adding your answer.

Traffic: 1746 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6