I have two data tables. A table with customer orders (it shows a customer ID, and the order date when a purchase was made) and a table with customer segmentation (it shows in which segment a customer was classified as in a certain time period).
I want to add the segment from data table 2) as a new variable in data table 1) but of course only the segment the customer was in at the time of the order.
Customer_Orders <- data.table(
customer_ID = c("A", "A"),
order_date = c("2017-06-30", "2019-07-30")
)
head(Customer_Orders)
customer_ID order_date
1: A 2017-06-30
2: A 2018-07-30
Customer_Segmentation <- data.table(
customer_ID = c("A", "A", "A"),
segment = c("1", "2", "3"),
valid_from = c("2017-01-01", "2018-01-01", "2019-01-01"),
valid_until = c("2017-12-31", "2018-12-31", "2019-12-31")
)
head(Customer_Segmentation)
customer_ID segment valid_from valid_until
1: A 1 2017-01-01 2017-12-31
2: A 2 2018-01-01 2018-12-31
3: A 3 2019-01-01 2019-12-31
This here is the manually constructed result I´m looking for
Result <- data.table(
customer_ID = c("A", "A"),
order_date = c("2017-06-30", "2019-07-30"),
segment = c(1, 3)
)
head(Result)
customer_ID order_date segment
1: A 2017-06-30 1
2: A 2019-07-30 3
Currently, my solution consists of doing a right-join to basically add all possible segments to each line in the customer orders table, and then exclude all rows where the order date is not in between the period of the segment. However, as my dataset is huge, this is a really slow and cumbersome solution