Question

We were trying to program object oriented programming in R, using S4 methods. During our programming process, we came across some problems. Apparently, the use of S4 methods is not very well documented on the internet yet, therefore we hope that we can get answers to some of our questions here.

First question:

We were trying to make a vector/array/list.. of empty S4 objects. Searching the internet brought us to the following question in this forum:

Create a vector of empty S4 objects

As (similarly) described in one of the answers to the question above, we used the following code to create a list of empty S4 objects:

setClass("Name", representation(pos_x = "numeric", pos_y = "numeric", found = 
"logical"), prototype(found = FALSE))

newList <- lapply(rep("Name", 2), new)

This works perfectly fine. However, when we are trying to call one slot (one variable) of the S4 method, this won't work. When we for example want to call the slot "pos_x", the following code

newList[1]@pos_x

is not working. The error message we receive is "Trying to get slot pos_x from an object of a basic class ("list") with no slots. So, it seems as if the slots were not assigned to the S4 method, although they are clearly defined in the list.

Does anyone know how we can call a slot from one of the S4-methods/objects of the list?

Second question:

We would like to test whether one of the elements of the list above equals "NULL", as we would like to create the objects later on.

To check this, we tried:

newList[1] == NULL 

This is however only resulting in "logical(0)". Does anyone know how to do this?

Suggestions, remarks and questions are very welcome.

Thanks a lot!

Was it helpful?

Solution

The problem is maybe due to the use of [ instead of [[.

The command newList[1] returns a list of length one, whereas the command newList[[1]] returns an element of the list. You should therefore try:

newList[[1]]@pos_x
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top