Parsing a Collection of Objects in R

时间:2016-08-30 04:34:19

标签: r collections

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.

1 个答案:

答案 0 :(得分:2)

使用双括号访问单个列表元素。与

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

你会得到:

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

解释

根据section 3.4 of the R Language Definition

  

对于列表,通常使用[[选择任何单个元素,而[返回所选元素的列表]。

请参阅this answer on SO