Yes, this works. Thank you so much!
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?
1 answer
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
Log in to answer this question.
Did not test your code but inside the loop you're missing a parenthesis right after
gr)to close thenamesfunction, and the last double quotes aftername3is a single quote.names(mcols(gr) = c("name1", "name2", "name3')should benames(mcols(gr)) = c("name1", "name2", "name3")this was an error while writing here. But my actual was code properly quoted and with parenthesis. And it does not work