Skip to content

Instantly share code, notes, and snippets.

@LogIN-
Created August 17, 2017 22:53
Show Gist options
  • Select an option

  • Save LogIN-/c90e4af5a77ba1a64d9a3b3028a147bb to your computer and use it in GitHub Desktop.

Select an option

Save LogIN-/c90e4af5a77ba1a64d9a3b3028a147bb to your computer and use it in GitHub Desktop.
Computes the intersection of lists in R
#!/usr/bin/Rscript --vanilla
#
# Author: LogIN- <info{@/at}ivantomic{.}com
# License: MIT
#
# Description:
#
# Computes the intersection of lists
# list_intersect() returns an list containing all the values of list1 that are present in all the arguments. Note that positions are NOT preserved.
#
# Parameters:
# list1
# The list with master values to check.
#
# list2
# An list to compare values against.
#
# ...
# A variable list of lists to compare.
#
# Return Values:
# Returns an list containing all of the values in list1 whose values exist in all of the parameters.
#
# Example:
# numb1 <- seq(50, 100, by=10)
# numb2 <- seq(70, 130, by=10)
# list_intersect(numb1, numb2)
list_intersect <- function(...){
args <- as.list(match.call())
args <- args[-1];
l <- length(args)
list1 <- eval(args[1][[1]])
args <- args[-1];
output <- list()
c <- 1
for (val_pos in 1:length(list1)) {
val <- list1[val_pos]
for (i in seq_along(args)) {
value <- args[i][[1]]
value <- eval(value)
for (val_s in value) {
if (val_s == val) {
if (i == l-1) {
output[c] = val_s
c = c +1
}
break
}
}
next
}
}
return(output)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment