MAnd
MAnd

Reputation: 157

In a R, how to choose the elements of a list of lists according to the value of an element of the sublists?

Let's say that in R we have the following list of lists, called A:

A <- list();
for (i in c(1:1000)) {
    A[[i]] <- list(sample(LETTERS, 1, T), runif(1, 1, 1000))
}

Such that for each element i of A, A[[i]][[1]] will be a randomly assigned letter and A[[i]][[2]] will be a randomly assigned number from 1 to 1000.

That being the case, is there a way, preferably without a loop, to dentify which elements j of A contain a list with second element greater than, say, 500? I.e. such that A[[j]][[2]] > 500?

If we were working with data-frames, we could use the function which. But I don't see how to achieve that with a list of lists.

Upvotes: 0

Views: 103

Answers (2)

Sandipan Dey
Sandipan Dey

Reputation: 23109

This will work too (to generate the logical vector):

unlist(A, recursive = FALSE)[seq(2,2*length(A),2)] > 500

Upvotes: 0

akrun
akrun

Reputation: 887391

We can use sapply to return a logical vector

i1 <- sapply(A, function(x)  x[[2]]>500)

Or without anonymous function call

i2 <- sapply(A, `[[`, 2)> 500

identical(i1, i2)
#[1] TRUE

This index can be used to filter the 'A'

A[i1]

Upvotes: 1

Related Questions