intersect()
intersect(x, y) The intersect() function returns the elements that appear in both of two vectors. It is useful for comparing IDs, categories, or labels shared between datasets.
Syntax
intersect(x, y)
Parameters
| Parameter | Type | Description |
|---|---|---|
x | vector | First input vector |
y | vector | Second input vector |
Examples
Basic usage
x <- c(1, 2, 3, 4)
y <- c(3, 4, 5, 6)
intersect(x, y)
# [1] 3 4
Character vectors
a <- c("apple", "banana", "cherry")
b <- c("banana", "cherry", "date")
intersect(a, b)
# [1] "banana" "cherry"
Finding common IDs
# Users who purchased both products
product_a_buyers <- c("user_1", "user_2", "user_3", "user_4")
product_b_buyers <- c("user_3", "user_4", "user_5", "user_6")
intersect(product_a_buyers, product_b_buyers)
# [1] "user_3" "user_4"
Common Patterns
Filtering based on another dataset
# Active users from a larger user list
all_users <- c("user_1", "user_2", "user_3", "user_4", "user_5")
active_users <- c("user_1", "user_3", "user_5")
intersect(all_users, active_users)
# [1] "user_1" "user_3" "user_5"
Common elements from multiple vectors
a <- c(1, 2, 3)
b <- c(2, 3, 4)
c <- c(3, 4, 5)
intersect(intersect(a, b), c)
# [1] 3