jreing
jreing

Reputation: 281

R- making a vector out of a list of classes

Let's say I define a class of some sort, That has fields name and grade for example. Now let's say I define a list of instances of this class.

How can I extract from this list a vector containing only the grades (with the same order they were in the list)?

Is there a fast way to do it without using a for loop?

Upvotes: 0

Views: 46

Answers (1)

JoFrhwld
JoFrhwld

Reputation: 9057

It's a bit tricky to say whether this will work without some sample code from you, but this might do the trick.

getGrade <- function(myObj){myObj$grade}
gradeList <- lapply(objList, getGrade)
gradeVec <- unlist(gradeList)

Or, collapsing that into a one liner.

gradeVec <- unlist(lapply(objList, function(x)x$grade))

Upvotes: 1

Related Questions