Search code examples
rlistr-s4

Can't use @ operator on s4 objects stored in a list in R?


This is hard to make a reproducible example of so I am sorry in advance.

I have a list called mp3List that contains wave objects. I generate it like this: It populates a list with 100 wave objects produced with readMP3.

mp3List <- vector("list", 100)
for(i in UrlReadNames)
{
  mp3List[which(UrlReadNames == i)]<-readMP3(i)
}

The structure of a wave object looks like this:

> str(ddd)
Formal class 'Wave' [package "tuneR"] with 6 slots
..@ left     : int [1:14772096] 0 0 0 0 0 0 0 0 0 0 ...
..@ right    : int [1:14772096] 0 0 0 0 0 0 0 0 0 0 ...
..@ stereo   : logi TRUE
..@ samp.rate: num 44100
..@ bit      : num 16
..@ pcm      : logi TRUE

The structure of a wave object in a list looks like this:

> str(mp3List[1])
List of 1

 $ :Formal class 'Wave' [package "tuneR"] with 6 slots
 .. ..@ left     : int [1:14772096] 0 0 0 0 0 0 0 0 0 0 ...
 .. ..@ right    : int [1:14772096] 0 0 0 0 0 0 0 0 0 0 ...
 .. ..@ stereo   : logi TRUE
 .. ..@ samp.rate: num 44100
 .. ..@ bit      : num 16
 .. ..@ pcm      : logi TRUE

Now I try to use mp3List[1]@left to access this part of the object, but I get this error: Error: Attempting to get a "left" slot from an object of a basic class ("list") without slots

I want to use @ on these objects in the list so I can write for loops to access every wave object in the list without having to pull out each one individually.


Solution

  • [ on a list returns a sublist. To extract an individual component, use [[.

    mp3List[[1]]@left