Question

I need to add a column in my sales table by matching 2 values with another table:

Example:

Table1 I need to add a column on this table

       PRODUCT       STORE    SALES
        A              Z        2
        A              X        4      
        B              X        4 

Table2

       PRODUCT       STORE     TERMS
        A              Z        0
        A              X        1    
        B              X        3   

I know how to match 1 value from each table with the match function:

Table1$Terms=Table2$Terms[match(Table1$Product,Table2$Product)]

However, I need to match both the Product code and the Store code

Needed result:

       PRODUCT       STORE    SALES    TERMS
        A              Z        2       0
        A              X        4       1 
        B              X        4       3
Was it helpful?

Solution

Table1 <-  merge(Table1, Table2, by = c("PRODUCT", "STORE"), all.x = T)

##  PRODUCT STORE SALES TERMS
## 1       A     X     4     1
## 2       A     Z     2     0
## 3       B     X     4     3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top