Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find Intersect of a Vector and List of Vectors

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading