First, let's start with DataTable 1 (DF1) :
date id sales cost city name
1: 06/19/2016 1 149 101 MTL Bank1
2: 06/20/2016 1 150 102 MTL Bank1
3: 06/21/2016 1 151 104 MTL Bank1
4: 06/22/2016 1 152 107 MTL Bank1
5: 06/23/2016 1 155 99 MTL Bank1
6: 06/19/2016 2 84 55 NY Bank2
7: 06/20/2016 2 83 55 NY Bank2
8: 06/21/2016 2 80 56 NY Bank2
9: 06/22/2016 2 81 57 NY Bank2
10: 06/23/2016 2 97 58 NY Bank2
library(data.table)
DF1 <- data.table(c("06/19/2016", "06/20/2016", "06/21/2016", "06/22/2016",
"06/23/2016", "06/19/2016", "06/20/2016", "06/21/2016",
"06/22/2016", "06/23/2016"),
c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2),
c(149, 150, 151, 152, 155, 84, 83, 80, 81, 97),
c(101, 102, 104, 107, 99, 55, 55, 56, 57, 58),
c("MTL", "MTL", "MTL", "MTL", "MTL", "NY", "NY",
"NY", "NY", "NY"))
colnames(DF1) <- c("date", "id", "sales", "cost", "city")
I want to add the column name
shown above using the lookup table:
id name start_date end_date status
1: 1 Bank1 06/19/2016 06/25/2016 0
2: 2 Bank2 06/27/2016 06/27/2017 0
3: 3 Bank3 06/22/2016 06/24/2017 1
4: 4 Bank3 06/23/2016 12/23/2016 1
lookup <- data.table(c(1, 2, 3, 4),
c("Bank1", "Bank2", "Bank3", "Bank3"),
c("06/19/2016", "06/27/2016", "06/22/2016", "06/23/2016"),
c("06/25/2016", "06/27/2017", "06/24/2017", "12/23/2016"),
c("0", "0", "1", "1"))
colnames(lookup) <- c("id", "name", "start_date", "end_date", "status")
In that case, I would use the id to find the name. When I try merge
, I always have new rows in DF1 that contains NA.