Che dire di una funzione come questa
has_empty_list <- function(x) {
if(is.list(x)) {
if (length(x)==0) {
return(TRUE)
} else {
return(any(vapply(x, has_empty_list, logical(1))))
}
} else {
return(FALSE)
}
}
In sostanza si crea una funzione ricorsiva per cercare liste di lunghezza 0.
has_empty_list(list(list("foo", "bar", "baz", list(list()))))
# TRUE
has_empty_list(list(list("foo", "bar", "baz", list(list(4)))))
# FALSE
Ed ecco una modifica per trovare l'indice della lista vuota
find_empty_list <- function(x, index=c()) {
if(is.list(x)) {
#list
if (length(x)==0) {
if (length(index)==0) {
return(0)
} else {
return(index)
}
} else {
m <- Map(find_empty_list, x, lapply(seq_along(x), function(i) append(index,i)))
# return the most deeply nested
return(m[[which.max(lengths(m))]])
}
} else {
return(numeric())
}
}
Questo dovrebbe restituire un vettore dell'indice che è possibile utilizzare per trovare il vuoto elenco. Ad esempio
(i <- find_empty_list(mylist))
# [1] 1 4 1
mylist[[i]]
# list()
Se il primo parametro stesso è un elenco vuoto, esso ritorna 0
find_empty_list(list())
# 0
e se non esiste un elenco vuoto, dovrebbe restituire un vettore vuoto
find_empty_list(list(1:3, list("c", a~b)))
# numeric()
@MrFlick Sì, questo è quello che sto cercando –