Skip to content

Instantly share code, notes, and snippets.

@MrFlick
Created June 8, 2023 14:17
Show Gist options
  • Save MrFlick/685e62e2f16461dcd6de142596b6bad6 to your computer and use it in GitHub Desktop.
Save MrFlick/685e62e2f16461dcd6de142596b6bad6 to your computer and use it in GitHub Desktop.
Find index of name in nested list
find_name_index <- function(haystack, needle, idx=c()) {
if (hasName(haystack, needle)) {
c(idx, which(names(haystack)==needle))
} else if (is.list(haystack)) {
for (i in seq_along(haystack)) {
obj <- haystack[[i]]
ret <- Recall(obj, needle, c(idx,i))
if (!is.null(ret)) return(ret)
}
} else {
NULL
}
}
my_list <- list(
"first_node" = list(
"group_a" = list(
"E001" = 1:5,
"E002" = list(
"F001" = 6:10,
"F002" = 11:15
)
),
"group_b" = list(
"XY01" = list(
"Z1" = LETTERS[1:5],
"Z2" = LETTERS[6:10],
"Z3" = list(
"ZZ1" = LETTERS[1],
"ZZ2" = LETTERS[2],
"ZZ3" = LETTERS[3]
)
),
"YZ" = LETTERS[11:15]
),
"group_c" = list(
"QQQQ" = list(
"RRRR" = 200:300
)
)
),
"second_node" = list(
"group_d" = list(
"L1" = 99:101,
"L2" = 12
)
)
)
pos <- find_name_index(my_list, "XY01")
pos
# [1] 1 2 1
my_list[[pos]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment