1

I've been looking for a simple (i.e. base R) function (or combination thereof) to extract the indices of the non-null items of a 2-dimension list but didn't find anything.

So I've built the following function but I have the strong feeling I am thereby reinventing the wheel:

MyList <- vector("list", length = 10)
MyList[[2]] <- 785
MyList[[9]] <- list(85, 4, 15, 10)

counter <- 0
non_null_indices <- unlist(lapply(X = MyList, FUN = function(List.Item){
    counter <<- counter + 1
    if(!is.null(List.Item)) return(counter)
}))
non_null_indices

Do you know an alternative way, more in the base R spirit, to do this?

Olivier7121
  • 151
  • 1
  • 11

1 Answers1

1

You can use %in% with which.

which(!MyList %in% list(NULL))
#[1] 2 9

or

which(!sapply(MyList, is.null))

or

which(!vapply(MyList, is.null, FALSE))

Alternatively you can use lengths like shown in a comment from @Gerald T (Thanks!), but this will fail in case the list contains e.g. numeric(0).

which(lengths(MyList) > 0)
#[1] 2 9
GKi
  • 37,245
  • 2
  • 26
  • 48