簡體   English   中英

為 R 中的列表列表中的列表提供正確匹配

[英]Providing the correct match for a list in a list of lists in R

我在 R 中有一個列表:

a <- list(x=0, y=c(1,2,3), z=4)
b <- list(x=1, y=c(1,2,3), z=44)
c <- list(x=2, y=c(1,2,3), z=444)
L <- list(a,b,c)

對於給定的列表,說

l <- list(x=0, y=c(1,2,3), z=4)

我知道想要找到L的正確索引,我們在其中找到等於l的相應列表。

當然,我可以使用循環,但由於L非常大,我需要一個更快的解決方案。 (這里的列表甚至是正確的選擇嗎?)

我們可以使用與base R identicalstack

which(sapply(L, function(x) identical(stack(l), stack(x))))
#[1] 1

或者更緊湊

which(sapply(L, identical, l))
#[1] 1

使用mapply將每個元素與l逐一比較。 如果您unlist ,則all內容都應為TRUE sapply周圍使用which最后給出匹配元素的數量。

f <- function(x) all(unlist(mapply(`==`, x, l)))

which(sapply(L, f))
# [1] 1

數據:

L <- list(list(x = 0, y = c(1, 2, 3), z = 4), list(x = 1, y = c(1, 
2, 3), z = 44), list(x = 2, y = c(1, 2, 3), z = 444))

l <- list(x = 0, y = c(1, 2, 3), z = 4)

也許你可以嘗試像下面這樣mapply

> which(mapply(identical, L, list(l)))
[1] 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM