Home > Software design >  Find Intersect of a Vector and List of Vectors
Find Intersect of a Vector and List of Vectors

Time:07-09

I have a vector of various foods that I need to sort, as follows:

myVector <- c("Banana", "Apple", "Spinach", "Lettuce", "Candy", "Soda")

I also have a list of foods that have been categorized as follows:

myList <- list(Fruits = c("Orange", "Watermelon", "Banana", "Grape", "Apple", "Strawberry"), 
               Veggies = c("Spinach", "Onion", "Carrot", "Lettuce", "Sprouts", "Cucumber"), 
               Other = c("Soda", "Milk", "Water", "Candy"))

Id like to find the intersect of myVector with each element in the list without having to manually type out multiple intersect statements like intersect(myList[[1]], myVector), intersect(myList[[2]], myVector) etc. because as I analyze different texts, myList can vary in the number of elements inside. Questions like this one were somewhat helpful but I don't wish to compare the vectors within myList to each other, I solely want to compare each vector in myList to myVector.

CodePudding user response:

We could do

lapply(myList, intersect, y = myVector)
#$Fruits
#[1] "Banana" "Apple" 
#
#$Veggies
#[1] "Spinach" "Lettuce"
#
#$Other
#[1] "Soda"  "Candy"

Explanation: elements of myList are passed to x one by one; myVector is passed to y.

## check arguments of `intersect()`
args(intersect)
#function (x, y)
  • Related