Thank you for all supporters' wonderful answers.
Let me post my own solution by base R as below;
cbnl <- list(
c("A", "B"), c("B", "A"), c("C", "D"), c("E", "D"), c("F", "G"), c("H", "I"),
c("J", "K"), c("I", "H"), c("K", "J"), c("G", "F"), c("D", "C"), c("E", "C"),
c("D", "E"), c("C", "E")
)
repeat {
# Get A Count Table
tbl <- table(unlist(cbnl))
# No Duplicated Items Then break Out
if (length(tbl[tbl > 1]) == 0) { break }
# Take A First Duplicated Item And Get the Index
idx <- which(sapply(seq_len(length(cbnl)), function(i) {
any(cbnl[[i]] == names(tbl[tbl > 1])[1])
}))
# Create New vector By Taking Union
newvec <- sort(unique(unlist(cbnl[idx])))
# Append newvec To cbnl And Remove Original vectors
cbnl <- c(cbnl, list(newvec))[-idx]
}
cbnl
The result is
[[1]]
[1] "A" "B"
[[2]]
[1] "C" "D" "E"
[[3]]
[1] "F" "G"
[[4]]
[1] "H" "I"
[[5]]
[1] "J" "K"
Here is data.table version.
cbn <- data.table(
item1 = c("A", "B", "C", "E", "F", "H", "J", "I", "K", "G", "D", "E", "D", "C"),
item2 = c("B", "A", "D", "D", "G", "I", "K", "H", "J", "F", "C", "C", "E", "E")
)
repeat {
# Get A Count Table
tbl <- table(as.vector(as.matrix(cbn)))
# No Duplicated Items Then break Out
if (length(tbl[tbl > 1]) == 0) { break }
# Take A First Duplicated Item And Get Row Numbers Where The Item Is Located
idx <- which(cbn == names(tbl[tbl > 1])[1], arr.ind = TRUE)[, 1]
# Create New Row By Taking Union
newrow <- setDT(as.list(sort(unique(as.vector(as.matrix(cbn[idx]))))))
names(newrow) <- paste0("item", seq_len(ncol(newrow)))
# Append newrow To cbn And Remove Original Rows
cbn <- rbindlist(l = list(cbn, newrow), use.names = TRUE, fill = TRUE)[-idx]
}
cbn
This result is as below.
item1 item2 item3
1: A B <NA>
2: C D E
3: F G <NA>
4: H I <NA>
5: J K <NA>