Reputation: 2524
I have a list where each element is a string. It happens that some of the elements are an empty character vector.
I want to get the indices of all those empty elements, but haven't found a syntax which delivers them.
my.list <- lapply(c("I", "am", "not", "empty"), function(x) x)
my.list[[5]] <- character(0)
my.list[[6]] <- character(0)
All things I've tried (such as my.list==""
, my.list==character(0)
) deliver something entirely different. If I unlist the list, it suddenly misses the empty elements and is only 4 elements long.
What is the correct syntax to find the empty character vectors?
Upvotes: 1
Views: 1879
Reputation: 31161
You can use R
3.2
version, from which lengths
function is available:
which(!lengths(my.list))
[1] 5 6
Upvotes: 3
Reputation: 15395
You could use length
:
lapply(my.list, length) == 0
For character vectors specifically,
f <- function(v){
is.character(v) && length(v) == 0
}
vapply(my.list, f, logical(1))
Mind you, Richard Telford's comment is the best answer to your question.
Upvotes: 1