從R中的類引用列表中獲取類引用字段的最小值 (Get min value of a class reference field from a list of class references in R)


問題描述

從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...

(by SherlockEdwardJustin)

參考文件

  1. Get min value of a class reference field from a list of class references in R (CC BY‑SA 3.0/4.0)

#R #for-loop






相關問題

如何將均值、標準差等函數應用於整個矩陣 (How to apply mean, sd etc. function to a whole matrix)

Tạo các thùng của mỗi hàng trong bảng và vẽ hình thanh ngăn xếp trong R (Make bins of each table row and draw stack bar figure in R)

Reading not quite correct .csv file in R (Reading not quite correct .csv file in R)

包'treemap'中的線條粗細 (Thickness of lines in Package ‘treemap’)

是否需要帶有 awk 的預處理文件,或者可以直接在 R 中完成? (Is preprocessing file with awk needed or it can be done directly in R?)

rpivotTable 選擇元素下拉菜單 (rpivotTable select elements drop down menu)

優化性能 - Shiny 中的大文件輸入 (Optimizing Performance - Large File Input in Shiny)

數值取決於所應用的應用系列,R (Numeric values depending of apply family applied, R)

如何記錄全年的值? (How to note the values across year?)

R中的線性搜索 (Linear search in R)

在 dplyr/purrr 工作流程中動態連接多個數據集 (Dynamically join multiple datasets in a dplyr/purrr workflow)

如何將行值更改為列名 (R) (How change Row values to Column names (R))







留言討論