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 ?
If a list contains NULL then we might want to replace it with another value or remove it from the list if we do not have any replacement for it. To remove the NULL value from a list, we can use the negation of sapply with is. NULL.
Description. NULL represents the null object in R. NULL is used mainly to represent the lists with zero length, and is often returned by expressions and functions whose value is undefined.
The easiest way to remove none from list in Python is by using the list filter() method. The list filter() method takes two parameters as function and iterator. To remove none values from the list we provide none as the function to filter() method and the list which contains none values.
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"
Try:
myList <- list(NULL, c(5,4,3), NULL, 25)
Filter(Negate(is.null), myList)
If you don't care of the result structure , you can just unlist
:
unlist(mylist)
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)
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 :)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With