I need to combine interconnected list elements to form distinct elements in base R with no additional packages required (while removing NA and zero-length elements).
Edit: I look for flexibility of data types (character, numeric etc), lists below augmented.
The lists:
list(c(1),c(1,2),c(1,2),c(2,3,4),c(8,9,10),c(10,11),c(NA))
list(c("a"),c("a","b"),c("a","b"),c("b","c","d"),c("h","i","j"),c("j","k"),c(NA))
...should become:
list(c(1,2,3,4),c(8,9,10,11))
list(c("a","b","c","d"),c("h","i","j","k"))
This is my solution so far which seem to work well:
ml <- list(c(1),c(1,2),c(1,2),c(2,3,4),c(8,9,10),c(10,11),c(NA))
# Remove duplicates
ml <- ml[!duplicated(ml)]
# Combine connected list elements
for (l1 in seq(1,length(ml))){
for (l2 in seq(1,length(ml))){
if (l1 != l2){
if(any(ml[[l2]] %in% ml[[l1]])){
ml[[l1]] <- sort(unique(c(ml[[l1]],ml[[l2]])))
ml[[l2]] <- NA
}
}
}
}
# Clean up list (remove NA, and zero-length elements)
ml <- Filter(Negate(anyNA), ml)
ml <- ml[lapply(ml, length)>0]
Is there any way to achieve the required result with fewer lines of code?


