繁体   English   中英

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

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

我有很大的列表,但是一些元素(位置)是NULL,在那里没有任何意义。 我想只提取我的列表中的一部分,这是非空的。 这是我的努力,但我遇到了错误:

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

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

有人会帮我实现吗?

你可以在这里使用is.null的逻辑否定。 这可以通过vapply应用于列表,我们可以使用[返回非null元素[

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

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

which(x != NULL)

可以使用“which”函数提取列表中的null enteries索引,而不是使用“ - ”将它们包含在新列表中。

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

应该做的工作:)

试试这个:

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

甚至这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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