我有一个非常大的列表,但其中一些元素(位置)是NULL,表示里面没有任何内容。 我想提取列表中非空的部分。这是我的尝试,但是我遇到了错误:
ind<-sapply(mylist, function() which(x)!=NULL)
list<-mylist[ind]
#Error in which(x) : argument to 'which' is not logical
有人可以帮我实现吗?(涉及IT技术)
我有一个非常大的列表,但其中一些元素(位置)是NULL,表示里面没有任何内容。 我想提取列表中非空的部分。这是我的尝试,但是我遇到了错误:
ind<-sapply(mylist, function() which(x)!=NULL)
list<-mylist[ind]
#Error in which(x) : argument to 'which' is not logical
is.null
,然后通过vapply
作用于列表,最后使用[
返回非空元素。(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"
尝试:
myList <- list(NULL, c(5,4,3), NULL, 25)
Filter(Negate(is.null), myList)
unlist
来简化:unlist(mylist)
试试这个:
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()
which
函数中:
which(x != NULL)
new_list=list[-which(is.null(list[]))]
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