-2

I have two data frames, appointment and transaction. Here Chart Number is matching the variable in both data frame.

I need to select first row in appointment table and get chart number and appointment date, then match this chart number to transaction table and get all transaction details. After getting all transaction details, compare appointment date to all transaction dates and if any transaction happened within 15 days then return 1 otherwise return 0 for that particular chart number in appointment table.

How can I use nested for loop or any other functions for this scenario?

I have used the following code

for(i in 1:nrow(a))
{
  appt <- a
  chart_number <- a[i, "Chart Number"]
  appointmentdate <- a[i, "Date"]

  trns <- subset(t, "Chart Number" == chart_number) 
  trns1 <- trns["Date"]
  out <- subset(trns1, as.Date(trns1$Date) >= as.Date(appointmentdate) & 
   as.Date(trns1$Date) <= as.Date(appointmentdate) + days(15))

  if(nrow(out) > 0)
  {
    appt$trns <- 1
  } else
    appt$trns <- 0 
}

enter image description here

Appointment table:

Chart number Date 1234dt 26/05/2015 001imp 28/06/2015 Ranj001 03/08/2015 Hath004 06/10/2015

Transaction table

Chart number Date 1234dt 26/05/2015 1234dt 7/06/2015 1234dt 24/08/2015 001imp 15/07/2015 001imp 5/09/2015 Ranj001 4/08/2015 Ranj001 29/08/2015

Miha
  • 2,559
  • 2
  • 19
  • 34

1 Answers1

0

First transform the 'Date' to a date format:

a$Date <- as.Date(a$Date, '%d-%m-%Y')
t$Date <- as.Date(t$Date, '%d-%m-%Y')

next use dplyr to do an inner join on the Chart Number

library(dplyr)
joined_table <- inner_join(x=a, y=t, by= c('Chart Number' = 'Chart.Number'))

Next subtract the two dates and test if the difference is <15 and create a new column Paid.

transform(joined_table , Paid = ifelse(Date.y - Date.x <= 15, 1, 0)

I did not test this example, because no data was provided. But I guess you get an idea on how you can solve the problem.

I hope I understood your questions correctly.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Linus
  • 705
  • 1
  • 10
  • 20