Find index position in nested lists for match
This can also be done with rrapply
in the rrapply
-package (extended version of base rapply
). The condition
argument decides to which elements f
should be applied, and the .xpos
argument in the f
function evaluates to the position of the element in the nested list. how = "flatten"
discards all list elements that do not satisfy condition
and returns a flattened list:
library(rrapply)
rrapply(f, condition = function(x) x == 11, f = function(x, .xpos) .xpos, how = "flatten")
#> [[1]]
#> [1] 2 3 2 1
foo = function(x, sep = ".") {
names(x) = paste0(seq_along(x))
while(any(sapply(x, class) == "list")) {
ind = sapply(x, class) == "list"
temp = unlist(x[ind], recursive = FALSE)
names(temp) = paste0(rep(names(x)[ind], lengths(x[ind])),
sep,
sequence(lengths(x[ind])))
x = c(x[!ind], temp)
}
return(x)
}
f2 = foo(f)
names(which(unlist(f2) == 11))
#[1] "2.3.2.1"
You can try melt()
from reshape2
:
melted_lst <- reshape2::melt(f)
melted_lst[sort(colnames(melted_lst))][melted_lst$value == 11, ]
L1 L2 L3 L4 value
7 2 3 2 1 11
Or with melt()
from data.table
(as mentioned by @IceCreamToucan):
melted_lst <- data.table::melt(f)
melted_lst[sort(colnames(melted_lst))][melted_lst$value == 11, ]