Fozefy
Fozefy

Reputation: 685

Accessing object methods from in a list

a bit new to R and I'm having some trouble accessing objects I've placed in a list.

I create my objects in a list like this:

myObjects <- vector("list", P)
for(i in 1:10){
  myObjects[[i]] <- new.myObject()
}

Then I want to access some methods I've created in the code, so I got to access them like this:

myObjects[1]@myMethod

However, when I do that I get the error: Error: trying to get slot "myMethod" from an object of a basic class ("list") with no slots

When I just have 1 object my code works fine, but after I've put it into a list I'm not sure how to get it back out of the list. I get that R deals with things as 'lists of size 1' a lot of the time, but it isn't working for me here. Is there a way to just get the object out of the list rather than a list of size 1 containing my object?

Upvotes: 1

Views: 175

Answers (1)

flodel
flodel

Reputation: 89057

The [ operator gives you a sublist: myObjects[1] is a list of length one.

[[ is the operator to get a list item: myObjects[[1]] is the first item in your list.

So myObjects[[1]]@myMethod is what should work here.

Upvotes: 1

Related Questions