Pam
Pam

Reputation: 111

Merge two data frames by id and date

I have two data frames. A:

id  date
1   2010-05-08
2   2012-08-08
3   2013-06-23

B:

id  date1
1   2010-05-09
2   2012-08-08

I need to left merge the two data frames by id and also where date in table 2=date in table1 +1 day. Further flag the row where the merge is TRUE.

The final output is A:

id  date           date1      flag
1   2010-05-08    2010-05-09   1
2   2012-08-08       NA        NA
3   2013-06-23       NA        NA

The code to generate the data-

A <- data.frame(customer = c(1,2,3),
                application_date = c("2010-05-08", "2012-08-08", "2013-06-23"))
B <- data.frame(customer = c(1,2),
                application_date = c("2010-05-09", "2012-08-08"))

Upvotes: 1

Views: 149

Answers (3)

chinsoon12
chinsoon12

Reputation: 25225

If you dont mind updating A directly by reference, here is an update join option:

library(data.table)
setDT(A)[, d := dateA + 1L]
setDT(B)
A[B, on=.(id, d=dateB), c("dateB", "flag") := .(dateB, 1L)]

data:

A <- data.frame(id = c(1,2,3),
    dateA = as.Date(c("2010-05-08", "2012-08-08", "2013-06-23")))
B <- data.frame(id = c(1,2),
    dateB = as.Date(c("2010-05-09", "2012-08-08")))

Upvotes: 1

Eric
Eric

Reputation: 2849

How about this?

DATA:

A <- data.frame(customer = c(1,2,3),
                application_date = c("2010-05-08", "2012-08-08", "2013-06-23"))
B <- data.frame(customer = c(1,2),
                application_date = c("2010-05-09", "2012-08-08"))

DPLYR:

library(dplyr)

    data <- left_join(A, B, by = "customer")
    data %>% 
      mutate(logic = if_else(as.Date(data$application_date.x) + 1 == as.Date(data$application_date.y), 1, 0)) %>% 
      rename("id" = "customer",
             "date" = "application_date.x",
             "date1" = "application_date.y",
             "flag" = "logic")

Output:

 id       date          date1         flag
 1       2010-05-08     2010-05-09    1 
 2       2012-08-08     2012-08-08    0 
 3       2013-06-23     <NA>          NA

DATA.TABLE:

library(data.table)

data_2 <- merge.data.table(A, B, by = "customer", all.x=TRUE)
data_2[, logic:= (ifelse(as.Date(data$application_date.x) + 1 == as.Date(data$application_date.y), 1, 0))]
setnames(data_2, old = c("customer", "application_date.x", "application_date.y", "logic"), 
                 new = c("id", "date", "date1", "flag"))

Output:

 id       date          date1         flag
 1       2010-05-08     2010-05-09    1 
 2       2012-08-08     2012-08-08    0 
 3       2013-06-23     <NA>          NA

Upvotes: 1

jnordeman
jnordeman

Reputation: 139

Using data.table:

data <- merge(A, B, by = "customer",all.x = TRUE)
library(data.table)

setDT(data)
data[as.Date(application_date.x)+1==application_date.y,flag:=1]
data[as.Date(application_date.x)+1!=application_date.y,flag:=0]
data <- data[,.(id=customer, date=application_date.x,date1=application_date.y,flag)]
data

Upvotes: 0

Related Questions