[英]Find Intersect of a Vector and List of Vectors
我有一個需要分類的各種食物的向量,如下所示:
myVector <- c("Banana", "Apple", "Spinach", "Lettuce", "Candy", "Soda")
我還有一份食物清單,分類如下:
myList <- list(Fruits = c("Orange", "Watermelon", "Banana", "Grape", "Apple", "Strawberry"),
Veggies = c("Spinach", "Onion", "Carrot", "Lettuce", "Sprouts", "Cucumber"),
Other = c("Soda", "Milk", "Water", "Candy"))
我想找到 myVector 與列表中每個元素的交集,而不必手動輸入多個 intersect 語句,例如intersect(myList[[1]], myVector)
, intersect(myList[[2]], myVector)
等,因為當我分析不同的文本時, myList
中的元素數量可能會有所不同。 像這樣的問題有點幫助,但我不想將 myList 中的向量相互比較,我只想將 myList 中的每個向量與 myVector 進行比較。
我們可以做
lapply(myList, intersect, y = myVector)
#$Fruits
#[1] "Banana" "Apple"
#
#$Veggies
#[1] "Spinach" "Lettuce"
#
#$Other
#[1] "Soda" "Candy"
解釋: myList
的元素一個一個傳給x
; myVector
被傳遞給y
。
## check arguments of `intersect()`
args(intersect)
#function (x, y)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.