Reputation: 339
I have a list
with length
of 14. Within each row, some of them are NULL
value, and some of them have multiple numbers. This is the list:
> start_positions
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
[[4]]
[1] 1517
[[5]]
NULL
[[6]]
NULL
[[7]]
NULL
[[8]]
NULL
[[9]]
[1] 1410
[[10]]
[1] 5995
[[11]]
NULL
[[12]]
[1] 13880 24631
[[13]]
NULL
[[14]]
[1] 18622
I want to unlist it and delete those NULL
values,but keep the number of the order of list
, like this:
list start_positions
4 1517
9 1410
10 5995
12 13880
12 24631
14 18622
I tried rbind()
and do.call()
with unlist()
, but it just gave me only one column and rank it from 1. (I think I should name each one of the row? but I don't know how.)
Upvotes: 0
Views: 78
Reputation: 193517
You'll get a warning because of the NULL
values, but you can use stack
:
myList <- list(NULL, NULL, 1, 2, NULL, c(3, 4)) ## Sample data
stack(setNames(myList, seq_along(myList)))
# values ind
# 1 1 3
# 2 2 4
# 3 3 6
# 4 4 6
# Warning message:
# In stack.default(setNames(myList, seq_along(myList))) :
# non-vector elements will be ignored
If you want to avoid the warning, you can subset the list after naming it:
names(myList) <- seq_along(myList)
stack(myList[!sapply(myList, is.null)])
Note that in any case stack
needs names
. In the first example, I added them "on the fly" using setNames
, and in the second example, I added them directly.
Upvotes: 1