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?