简体   繁体   中英

How to extract the non-empty elements of list in R?

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 ?

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)

如果您不关心结果结构,可以unlist

unlist(mylist)

错误的含义是您的括号不正确,您要测试的条件必须在which函数中:

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()
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM