ChrisD
ChrisD

Reputation: 674

How to create new column in data.table based on presence of value in another data.table

I have two data.tables A and B:

A               B                          A
---------       -----------------          -----------------
Col1 Col2       Col1 Col2                  Col1 Col2 Col3  
A    1          A    popular               A    1    popular 
B    2          B    moderate        ->    B    2    moderate
C    3          C    not popular           .    .    .
D    4          D    popular               .    .    .

For each value in col1 of A, I want to check for its existence in col1 of B. If it's there, then create a third column in A based on the value in col2 of B. How can I achieve this?

Upvotes: 1

Views: 250

Answers (1)

akrun
akrun

Reputation: 887088

We can use a join

library(data.table)
setDT(A)[B, Col3 := Col2,on = .(Col1)]

Upvotes: 1

Related Questions