Outersection in R

Outersection of two or more vectors

To get the non common elements of two or more vectors

outersect <- function(x, y, ...) {
    big.vec <- c(x, y, ...)
    duplicates <- big.vec[duplicated(big.vec)]
    return(setdiff(big.vec, unique(duplicates)))
}

> v1 <- c(1, 2, 3)
> v2 <- c(2, 3, 4)
> outersect(v1, v2)
[1] 1 4
> v3 <- c(0, 1, 4, 5)
> outersect(v1, v2, v3)
[1] 0 5

Outersection of a list of vectors

To get the non common elements of a list of vectors

outersect.list <- function(list.vec) {
    big.vec <- unlist(list.vec)
    duplicates <- big.vec[duplicated(big.vec)]
    return(setdiff(big.vec, unique(duplicates)))
}

> ll <- list()
> ll$c1 <- c(1, 2, 3)
> ll$c2 <- c(2, 3, 4)
> outersect.list(ll)
[1] 1 4
> ll$c3 <- c(3, 4, 5)
> outersect.list(ll)
[1] 1 5
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: