[英]Accessing R list elements through function parameters
我有一個 R 列表,如下所示
> str(prices)
List of 4
$ ID : int 102894616
$ delay: int 8
$ 47973 :List of 12
..$ id : int 47973
..$ index : int 2
..$ matched: num 5817
$ 47972 :List of 12
..
顯然,我可以通過如prices$"47973"$id 訪問任何元素。
但是,我將如何編寫一個參數化對該列表的訪問的 function? 例如帶有簽名的訪問 function:
access <- function(index1, index2) { .. }
可以按如下方式使用:
> access("47973", "matched")
5817
這似乎很微不足道,但我沒有寫出這樣的 function。 感謝您的任何指示。
使用'[['
而不是'$'
似乎有效:
prices <- list(
`47973` = list( id = 1, matched = 2))
access <- function(index1, index2) prices[[index1]][[index2]]
access("47973","matched")
至於為什么這樣做而不是: access <- function(index1, index2) prices$index1$index2
(我認為這是你嘗試過的?)這是因為這里index1
和index2
沒有被評估。 也就是說,它在列表中搜索一個名為index1
的元素,而不是這個 object 的計算結果。
您可以利用[[
接受向量,遞歸使用的事實:
prices <- list(
`47973` = list( id = 1, matched = 2))
prices[[c("47973", "matched")]]
# 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.