Pat M Pat M - 1 year ago 98
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(
fields = list(myVar = "data.frame"),
methods = list(

setData = function(teamNames,participants) {
lenTitles = length(teamNames)
lenDesc = length(participants)
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(
fields = list(myVar = "numeric"),
methods = list(
myInitializer = function() {
teamNames <- c("A Team", "B Team")
participants <- c("Aaron Atkinson", "Barbara Bellemont")
output$setData(teamNames, participants)

myObject<- MyClass$new(myVar = 1)

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 **"
Reference class object of class "MyNewClass"
Field "team":
[1] "A Team"
Field "player":
[1] "Aaron Atkinson"

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

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

Thank you for your suggestions.

Answer Source

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"


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download