简体   繁体   中英

Access slot from S4 object in a list within an R loop

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM