問題描述
從R中的類引用列表中獲取類引用字段的最小值 (Get min value of a class reference field from a list of class references in R)
R Beginner here.
I have a list of class references. Each class has a field, "x". I want to find the class reference which has the lowest "x" in the list.
In python I would do this:
return min(item.x for item in myList)
I'm not sure if there is specific terminology for the type of statement above (if someone knows I would like to know), but is there are way of doing a similar type of thing in R ?
If not, what would be the best way to achieve this in R ?
** Edit re. Justins comment
Here is how the list is created ..
mylist <‑ list()
for (i in 1:10){
mylist <‑ c(mylist, MyClass$new())
}
where:
MyClass <‑ setRefClass("MyClass",
fields = list(x = "numeric"),
methods = list(
initialize = function(){
x <<‑ sample(0:100, 1)
}
)
)
Many thanks
‑‑‑‑‑
參考解法
方法 1:
If you want to get to the entire instance of MyClass with the lowest value of x, as opposed to just the minimum value of x (you seem to be looking for the former), consider using which.min
in something like the following:
mylist[[which.min(lapply(mylist, function(myClass) myClass$x))]]
方法 2:
Your list is just a list which can be accessed using its named components:
> mylist[[1]]$x
[1] 66
>
so the answer in my comment will work:
> min(unlist(lapply(mylist, function(y) y$x)))
[1] 20
I'll leave the details to someone who knows R's OO better than I do...