How to check the existence of elements of list in r

matrix, r

Solution

tl;dr: If you want to check if element `n` exists, even if checking at end of a list or an empty list, use:

length(mylist) >= n   # TRUE indicates exists. FALSE indicates DNE

For nested lists, make sure to check the correct list. eg:

 length(outerlist[[innerlist]]) >= n

NULL in lists in R has some differences from what one is used to in other languages. For example, if we replace the element of a list by NULL, all subsequent elements are shifted over, and the list is left with a length of one less.

# SAMPLE DATA
mylist <- as.list(LETTERS[1:5])

    [[1]]
    [1] "A"

    [[2]]
    [1] "B"

    [[3]]
    [1] "C"

    [[4]]
    [1] "D"

    [[5]]
    [1] "E"

Testing for NULL in elements 3 & 6. Not quite the information we are looking for.

is.null(mylist[[3]])
# FALSE

is.null(mylist[[6]])
# Error in mylist[[6]] : subscript out of bounds

Instead we check the length of the list:

length(mylist) >= 3  # TRUE
length(mylist) >= 5  # TRUE
length(mylist) >= 6  # FALSE

Removing the 3rd element. Notice that the "empty slot" is not preserved. (ie, element 4, becomes element 3, etc..)

mylist[[3]] <- NULL

  [[1]]
  [1] "A"

  [[2]]
  [1] "B"

  [[3]]
  [1] "D"

  [[4]]
  [1] "E"


length(mylist) >= 3  # TRUE
length(mylist) >= 5  # FALSE
length(mylist) >= 6  # FALSE

An empty list will have length of 0

emptyList <- list()
length(emptyList)  # 0

nestedList <- list( letters=list("A", "B", "C"), empty=list(), words=list("Hello", "World"))

length(nestedList)
  # [1] 3
lapply(nestedList, length)
  # $letters
  # [1] 3
  #
  # $empty
  # [1] 0
  #
  # $words
  # [1] 2

Note that you can incoporate NULL into a list. Which is when testing for NULL is applicable. For example:

myListWithNull <- list("A", "B", NULL, "D")

is.null(myListWithNull[[3]])
  # TRUE

length(myListWithNull) >= 3
  # TRUE

Problem

How can I check if an element of list exists or not. This is a list of lists so for example I want to check whether the third element l1[[3]] exists or not. I have tried is.null(l1[["3"]]) but it returns false no matter whether it exists or not and if I use is.null(l1[[3]]) it will give the error of subscript out of bind in case it does not exists but not TRUE. How should I che

Original source

Related problems