如何在R中提取非空元素的列表?

6

我有一个非常大的列表,但其中一些元素(位置)是NULL,表示里面没有任何内容。 我想提取列表中非空的部分。这是我的尝试,但是我遇到了错误:

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

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

有人可以帮我实现吗?(涉及IT技术)
7个回答

6
你可以使用逻辑非运算符来代替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"

4

尝试:

 myList <- list(NULL, c(5,4,3), NULL, 25)
 Filter(Negate(is.null), myList)

3
如果您不关心结果结构,您可以使用 unlist 来简化:
unlist(mylist)

我需要一种简单的方法来从列表中仅获取非空值,这个方法很好用!谢谢! - Berke

1

试试这个:

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

1
这个错误的意思是你的括号不正确,你想测试的条件必须放在which函数中:

which(x != NULL)


1
可以使用“which”函数提取列表中空条目的索引,并使用“-”将它们排除在新列表之外。
new_list=list[-which(is.null(list[]))] 

应该可以完成工作 :)

-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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接