从列表中访问对象方法

时间:2022-04-22 15:54:48

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

R有点新,我在访问列表中的对象时遇到了一些麻烦。

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

但是,当我这样做时,我得到错误:错误:尝试从没有插槽的基本类(“列表”)的对象获取插槽“myMethod”

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?

当我只有一个对象时,我的代码工作正常,但在我将它放入列表后,我不知道如何将其从列表中取出。我得到的R很多时候处理的东西都是“1号列表”,但这对我来说并不适用。有没有办法让对象从列表中取出而不是包含我的对象的大小为1的列表?

1 个解决方案

#1


1  

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

[运算符给出一个子列表:myObjects [1]是长度为1的列表。

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

[[是获取列表项的运算符:myObjects [[1]]是列表中的第一项。

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

所以myObjects [[1]] @ myMethod应该在这里起作用。

#1


1  

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

[运算符给出一个子列表:myObjects [1]是长度为1的列表。

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

[[是获取列表项的运算符:myObjects [[1]]是列表中的第一项。

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

所以myObjects [[1]] @ myMethod应该在这里起作用。