Reputation: 2307
I have a list which contain a list of list. The structure looks like this:
Is it possible to create a with none empty list of list in it?
I tried datalist2 <- datalist[!is.na(datalist[[]])]
which return 0 list, and datalist2 <- datalist[!is.na(datalist[[]])]
whih return 5 lists(no changes). How can I only get 3 lists?
Any suggestion?
Upvotes: 0
Views: 27
Reputation: 4841
You can use sapply
and length
and then select those with non-zero length:
# create an example
dat <- list(list(1:3), list(), list(letters[1:4]), list(LETTERS[1:4]),
list(), list())
str(dat)
#R> List of 6
#R> $ :List of 1
#R> ..$ : int [1:3] 1 2 3
#R> $ : list()
#R> $ :List of 1
#R> ..$ : chr [1:4] "a" "b" "c" "d"
#R> $ :List of 1
#R> ..$ : chr [1:4] "A" "B" "C" "D"
#R> $ : list()
#R> $ : list()
# get the non-empty lists
res <- dat[sapply(dat, length) > 0]
# show the results
str(res)
#R> List of 3
#R> $ :List of 1
#R> ..$ : int [1:3] 1 2 3
#R> $ :List of 1
#R> ..$ : chr [1:4] "a" "b" "c" "d"
#R> $ :List of 1
#R> ..$ : chr [1:4] "A" "B" "C" "D"
Upvotes: 1
Reputation: 2906
You might wanna use purrr
:
datalist2 <- datalist[!purrr:is_empty(datalist[[]])]
Don't know if it works though, could you please provide a sample?
Upvotes: 0