简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM