I am trying to access a specific slot from an object inside a list in an R loop:
mysamples<-'a_vcf', 'b_vcf', 'c_vcf'
for(i in mysamples){
vcf<-mget(i)
a<-vcf$i@rowRanges
}
But this is not working:
Error in eval(quote(list(...)), env) :
trying to get slot "rowRanges" from an object of a basic class ("NULL") with no slots
mget()
generates a list called vcf
which contains an S4 object named i
(for example: a_vcf
); but, using vcf$i
instead of vcf$a_vcf
does not work.
How can I solve this?
You cannot use the $
operator this way - you have to use the [[
operator instead. So if your structure is set up as you describe, that is you have lists called a_vcf
, b_vcf
, c_vcf
, each of which contains an element with the same name, then the following will work:
for(i in mysamples){
vcf <- mget(i)
a <- vcf[[i]]@rowRanges
}
However, please remember you are over-writing a
each time, so after the loop completes, you will only have the value of c_vcf$c_vcf@rowRanges
written to a
.