Get indices of elements in a list that do not contain any NA

Viewed 35

I have a list of vectors with varying lengths, some with numbers and some with NA. I want to get the indices of the list that do not have any NA.

m <- list(3, NA, c(NA, NA, NA), c(4,5), c(3, NA))

When I use is.na it still returns indices 3 and 5, even though the vectors contain NA.

which((!is.na(m)), TRUE)
[1] 1 3 4 5 

I would like to only return indices 1 and 4. How do I do this?

2 Answers

One easy way to iterate over the vectors in your list is with sapply. And then you can use anyNA to check if there are any NA values. Then negate that so you only find those that don't have NA values. You can do that all with

which(!sapply(m, anyNA))

Using aggregate

with(aggregate(cbind(values = !is.na(values)) ~ ind, 
       stack(setNames(m, seq_along(m))), FUN = all), ind[values])
Related