6

I have very big list, but some of the elements(positions) are NULL, means nothing inside there. I want just extract the part of my list, which is non-empty. Here is my effort, but I faced with error:

ind<-sapply(mylist, function() which(x)!=NULL)
list<-mylist[ind]

#Error in which(x) : argument to 'which' is not logical

Would someone help me to implement it ?

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
user2806363
  • 2,513
  • 8
  • 29
  • 48

7 Answers7

6

You can use the logical negation of is.null here. That can be applied over the list with vapply, and we can return the non-null elements with [

(mylist <- list(1:5, NULL, letters[1:5]))
# [[1]]
# [1] 1 2 3 4 5

# [[2]]
# NULL

# [[3]]
# [1] "a" "b" "c" "d" "e"

mylist[vapply(mylist, Negate(is.null), NA)]
# [[1]]
# [1] 1 2 3 4 5

# [[2]]
# [1] "a" "b" "c" "d" "e"
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
4

Try:

 myList <- list(NULL, c(5,4,3), NULL, 25)
 Filter(Negate(is.null), myList)
akrun
  • 874,273
  • 37
  • 540
  • 662
3

If you don't care of the result structure , you can just unlist:

unlist(mylist)
agstudy
  • 119,832
  • 17
  • 199
  • 261
  • I needed a simple way to only take out the non-null value from a list and this does the trick! thanks! – Berke Oct 28 '22 at 08:54
1

What the error means is that your brackets are not correct, the condition you want to test must be in the which function :

which(x != NULL)

Math
  • 2,399
  • 2
  • 20
  • 22
1

One can extract the indices of null enteries in the list using "which" function and not include them in the new list by using "-".

new_list=list[-which(is.null(list[]))] 

should do the job :)

Tom
  • 4,257
  • 6
  • 33
  • 49
Amit
  • 11
  • 1
1

Try this:

list(NULL, 1, 2, 3, NULL, 5) %>% 
     purrr::map_if(is.null, ~ NA_character_) %>% #convert NULL into NA
     is.na() %>% #find NA
     `!` %>%     #Negate
     which()     #get index of Non-NULLs

or even this:

list(NULL, 1, 2, 3, NULL, 5) %>% 
     purrr::map_lgl(is.null) %>% 
     `!` %>% #Negate 
     which()
slavakx
  • 21
  • 4
-1
MyList <- list(NULL, c(5, 4, 3), NULL, NULL)

[[1]]
NULL

[[2]]
[1] 5 4 3

[[3]]
NULL

[[4]]
NULL

MyList[!unlist(lapply(MyList,is.null))]

[[1]]
[1] 5 4 3
dondapati
  • 829
  • 6
  • 18