在R语言中如何高效检测所有元素均为integer(0)的列表?
integer(0) (Even as Factors) Got it, let's tackle this problem. Your example has a list where elements are factors with levels, but their underlying data is integer(0)—so we need a way to verify every element fits this exact scenario, not just any empty vector.
Step 1: Define a Helper Function for Single Elements
First, create a function that checks if a single element is effectively integer(0) (even when wrapped as a factor):
is_empty_integer <- function(x) { # Check two key things: length is 0, and converting to integer gives integer(0) length(x) == 0 && identical(as.integer(x), integer(0)) }
This works for both raw integer(0) values and factors that wrap integer(0) (like your example) because converting an empty factor to integer will return integer(0).
Step 2: Check All List Elements
Use sapply() to apply this function to every element in your list, then wrap it with all() to confirm every element passes the check:
Let's test this with your reproducible example:
set.seed(10) a <- list(a = as.factor(integer(0)), b = as.factor(sample(letters[1:5], 10, rep=T))) levels(a$a) <- levels(a$b) a$b <- as.factor(integer(0)) levels(a$b) <- levels(a$a) # Run the check all(sapply(a, is_empty_integer)) # Returns TRUE, which is correct—both elements are integer(0) wrapped as factors
Test a Counterexample
If we modify one element to have actual data, the check correctly returns FALSE:
# Update a$b to have non-empty factor data a$b <- as.factor(sample(letters[1:5], 3, rep=T)) all(sapply(a, is_empty_integer)) # Returns FALSE
Simplification (If You Know All Elements Are Factors)
If you're certain every element in the list is a factor, you can simplify the check to just verifying all lengths are 0 (since empty factors with levels still have length 0):
all(sapply(a, length) == 0)
But the helper function approach is more robust if your list might mix factor and raw integer types, or if you need to exclude other empty vectors (like character(0)).
内容的提问来源于stack exchange,提问作者mickkk

