R: removing NULL elements from a list

2020-01-30 08:00发布

mylist <- list(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
    123, NULL, 456)

> mylist
[[1]]
NULL

[[2]]
NULL

[[3]]
NULL

[[4]]
NULL

[[5]]
NULL

[[6]]
NULL

[[7]]
NULL

[[8]]
NULL

[[9]]
NULL

[[10]]
NULL

[[11]]
[1] 123

[[12]]
NULL

[[13]]
[1] 456

My list has 13 elements, 11 of which are NULL. I would like to remove them, but preserve the indices of the elements that are nonempty.

mylist2 = mylist[-which(sapply(mylist, is.null))]
> mylist2
[[1]]
[1] 123

[[2]]
[1] 456

This removes the NULL elements just fine, but I don't want the nonempty elements to be reindexed, i.e, I want mylist2 to look something like this, where the indices of the nonempty entries are preserved.

> mylist2
[[11]]
[1] 123

[[13]]
[1] 456

标签: r
8条回答
够拽才男人
2楼-- · 2020-01-30 08:56

here's a very simple way to do it using only base R functions:

names(mylist) <- 1:length(mylist)
mylist2 <- mylist[which(!sapply(mylist, is.null))]
查看更多
Root(大扎)
3楼-- · 2020-01-30 08:59

If you want to keep the names you can do

a <- list(NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 
          123, NULL, 456)
non_null_names <- which(!sapply(a, is.null))
a <- a[non_null_names]
names(a) <- non_null_names
a

You can then access the elements like so

a[['11']]
num <- 11
a[[as.character(num)]]
a[[as.character(11)]]
a$`11`

You can't get them in the neat [[11]], [[13]] notation, though, because those represent numerical indices.

查看更多
登录 后发表回答