I have a list that is the result of a row selection in a data frame. The issue is that sometimes there is no row to select and it returns a list in this form: a non-empty list with no actual content.
L <- list(combattech = character(0), damage = character(0), bonus = character(0),
range = structure(list(close = character(0), medium = character(0), far = character(0)),
row.names = integer(0), class = "data.frame"),
ammo = character(0), weight = character(0), name = character(0),
price = character(0), sf = character(0))
I want to verify if I actually have a meaningful result and not a list with all elements being empty vectors. But a list with empty vectors is not equivalent to an empty list:
length(L) == 0
#> [1] FALSE
does not give me TRUE
because the length is 9
not 0
.
Of course, I could simply check if length( which(...row selection...) )
before I pick the selection and usually I do, but in this case I do not have access to the original row indices.
all(sapply(L, length) == 0)
#> [1] FALSE
also does not work (i.e. returns FALSE
) because the nested data structure range
returns 3.
Created on 2020-06-28 by the reprex package (v0.3.0)
1) We can use rapply
to recursively walk the structure and return a flat result.
all(rapply(L, length) == 0)
## [1] TRUE
2) Another approach is to unlist
it first:
length(unlist(L)) == 0
## [1] TRUE