Reputation: 1460
To explain what I want to do exactly, I will use the following example:
a = list(x = 5, y = c(11, 12, 13))
b = list(x = 4.7, y = c(112, 5, 2))
c = list(x = 77, y = c(5, 1, 1))
d = list(x = 5, y = c(22, 11, 43))
test_list = list(a, b, c, d)
I have a nested list: test_list
. I would like to search vector 5
only in element x
in the tested_list, and return the indices of the list, e.g., here as c(1,4).
Thanks a lot.
Upvotes: 1
Views: 63
Reputation: 887118
As 'x' is of length
1 in each list
element, it may be better to do the comparison at once after extracting the element
which(sapply(test_list, `[[`, 'x')==5)
#[1] 1 4
Upvotes: 1
Reputation: 39858
Similarly, using purrr
:
which(map_lgl(test_list, ~ pluck(., "x") == 5))
[1] 1 4
Upvotes: 1
Reputation: 5456
Try:
which(vapply(test_list, function(x) x[["x"]] == 5, logical(1)))
Upvotes: 1
Reputation: 3162
I would try with lapply
like here:
a = list(x = 5, y = c(11, 12, 13))
b = list(x = 4.7, y = c(112, 5, 2))
c = list(x = 77, y = c(5, 1, 1))
d = list(x = 5, y = c(22, 11, 43))
test_list = list(a, b, c, d)
which(unlist(lapply(test_list, function(x) {
x$x == 5
})))
First you choose x
then for 5
then unlist
and then check which are TRUE
.
Upvotes: 2