Wang
Wang

Reputation: 1460

Search a vector in a specific element of a nested list in R

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

Answers (4)

akrun
akrun

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

tmfmnk
tmfmnk

Reputation: 39858

Similarly, using purrr:

which(map_lgl(test_list, ~ pluck(., "x") == 5))

[1] 1 4

Upvotes: 1

r.user.05apr
r.user.05apr

Reputation: 5456

Try:

 which(vapply(test_list, function(x) x[["x"]] == 5, logical(1)))

Upvotes: 1

Marta
Marta

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

Related Questions