找到分组变量的并集和交集

Find the union and intersection of grouped variables

我有两个合并的向量。 基本上,我想要一个函数来找到这两个向量(输出)的并集和交集。 似乎没有支持此功能的功能。知道如何执行所需的输出向量吗?

example1 <- c("18--25", "26--30", "31--50", "51+")
example2 <- c("18--23", "24--30", "31--65", "66+")

output <- c("18--23", "24--25", "26--30", "31--50", "51--65", "66+")

我们可以像这样删除重复项并每 2 个元素组合一个排序向量(R 4.0 版及更高版本用于管道 |>):

f <- function(x, y, sep, max){
  m <- paste0("\", max)
  gsub(m, "", c(x, y)) |>
    strsplit(sep, fixed = T) |>
    unlist(use.names = F) |>
    sort() |>
    unique() |>
    as.numeric() |>
    (\(.) tapply(., gl(length(.), 2, length(.)), paste, collapse = sep, simplify = T))() |>
    (\(.) .[!is.na(.)])() |>
    as.character() |>
    (\(.) {.[length(.)] <- paste0(.[length(.)], max) ; .})()
}  

# for older R versions
f <- function(x, y, sep, max){
  x <- gsub(paste0("\", max), "", c(x, y))
  x <- as.numeric(unique(sort(unlist(strsplit(x, sep, T), use.names = F))))
  x <- tapply(x, gl(length(x), 2L, length(x)), paste, collapse = sep, simplify = T)
  x <- as.character(x[!is.na(x)])
  x[length(x)] <- paste0(x[length(x)], max)
  x
}

f(example1, example2, "--", "+")
[1] "18--23" "24--25" "26--30" "31--50" "51--65" "66+"