Last active
December 1, 2022 13:36
-
-
Save btupper/032b7e6d894fcd86dec23f3d4a1b6d57 to your computer and use it in GitHub Desktop.
Set operations with multiple elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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