Skip to content

Instantly share code, notes, and snippets.

@btupper
Last active December 1, 2022 13:36
Show Gist options
  • Save btupper/032b7e6d894fcd86dec23f3d4a1b6d57 to your computer and use it in GitHub Desktop.
Save btupper/032b7e6d894fcd86dec23f3d4a1b6d57 to your computer and use it in GitHub Desktop.
Set operations with multiple elements
#' Compute the union of a list of vectors
#'
#' @param x a list of zero or more vectors
#' @return a vector of the union or NULL is the input is empty
munion <- function(x){
if (!is.list(x)) stop("input must be a list")
n <- length(x)
if (n == 0) return(NULL)
if (n == 1) return(x[[1]])
s <- x[[1]]
for (i in 2:n) s <- union(s, x[[i]])
s
}
#' Compute the intersection of a list of vectors
#'
#' @param x a list of zero or more vectors
#' @return a vector of the intersection or NULL is the input is empty
mintersect <- function(x){
n <- length(x)
if (n == 0) return(NULL)
if (n == 1) return(x[[1]])
s <- x[[1]]
for (i in 2:n) s <- intersect(s, x[[i]])
s
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment