Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding (and returning) the first element of a list that meets a (logical) test

Tags:

list

r

subset

As an example, I have a large list of vectors with various lengths (and some NULL) and would like to find the first list element with two elements. As in this post, I know that with a list you can use a similar approach by using sapply() and subsetting the first result. As the solution in the post linked above using match() doesn't work in this case, I'm curious if there is a more elegant (and more computationally efficient) way to achieve this.

A reproducible example


# some example data
x <- list(NULL, NULL, NA, rep("foo", 6), c("we want", "this one"),
           c(letters[1:10]), c("foo", "bar"), NULL)
x

# find the first element of length 2 using sapply and sub-setting to result #1
x[sapply(x, FUN=function(i) {length(i)==2})][[1]]

Or, as in @Josh O'Brien's answer to this post,

# get the index of the first element of length 2
seq_along(x)[sapply(x, FUN=function(i) {length(i)==2})]

Any thoughts or ideas?

like image 735
Cotton.Rockwood Avatar asked Dec 11 '22 04:12

Cotton.Rockwood


1 Answers

Do you want this?

Find(function(i) length(i) == 2, x) # [1] "we want"  "this one"
Position(function(i) length(i) == 2, x) # [1] 5
like image 136
Robert Krzyzanowski Avatar answered Jan 17 '23 05:01

Robert Krzyzanowski