Pat M Pat M - 3 months ago 6
R Question

Parsing a Collection of Objects in R

I am trying to parse out objects from a collection of objects when using the R programming language. My code sample below shows that the collection has data. However, I can't figure out how to extract and store data for a single object.

Here is a complete code sample which does run:

MyNewClass <- setRefClass(
"MyNewClass", fields = list( team = "character", player = "character" )
)

Output <- setRefClass(
"Output",
fields = list(myVar = "data.frame"),
methods = list(

setData = function(teamNames,participants) {
lenTitles = length(teamNames)
print(lenTitles)
lenDesc = length(participants)
myCollection<-c()
for(i in 1:lenTitles) {
myobj <- structure(list(title = teamNames[i],
description = participants[i]), class = "myclass")
myNewClass <- MyNewClass$new()
myNewClass$team <- teamNames[i];
myNewClass$player <- participants[i];
myCollection <- c(myCollection, myNewClass)
}
print("** Collection Data **")
print(myCollection) # This works

print("** Single Object Property **")
print(myCollection[1]$team) # This does not work.
}
)
)

MyClass <- setRefClass(
"MyClass",
fields = list(myVar = "numeric"),
methods = list(
myInitializer = function() {
teamNames <- c("A Team", "B Team")
participants <- c("Aaron Atkinson", "Barbara Bellemont")
output<-Output$new()
output$setData(teamNames, participants)
}
)
)

myObject<- MyClass$new(myVar = 1)
myObject$myInitializer()


The output shows that the collection has two objects but I have been unable to extract an object from the collection:

[1] 2
[1] "** Collection Data **"
[[1]]
Reference class object of class "MyNewClass"
Field "team":
[1] "A Team"
Field "player":
[1] "Aaron Atkinson"

[[2]]
Reference class object of class "MyNewClass"
Field "team":
[1] "B Team"
Field "player":
[1] "Barbara Bellemont"

[1] "** Single Object Property **"
NULL


Thank you for your suggestions.

Answer

Use double brackets to access a single list element. With

print("** Single Object Property **")
      print(myCollection[[1]]$team)   # This works

you will get:

[1] "** Single Object Property **"
[1] "A Team"

Explanation

According to section 3.4 of the R Language Definition

For lists, one generally uses [[ to select any single element, whereas [ returns a list of the selected elements.

Please, see also this answer on SO.