0

I have two different data frames. Lets say "Cases" and "test".

"Cases" Data Frame Looks like:

  Date          Death         Cured
  15-04-2020    5             2
  16-04-2020    4             3
  17-04-2020    2             5
  18-04-2020    5             10
  19-04-2020    7             13
  20-04-2020    4             12
  21-04-2020    6             13
  22-04-2020    4             13

"test" Data Frame Looks like:

  Date          Samples        Positive
  18/04/2020    50             15
  19/04/2020    60             20
  20/04/2020    70             16
  21/04/2020    80             19
  22/04/2020    90             17

I want to conditionally join these data frames. This means if Cases$Date == test$Date then join "Samples" and "Positive" column to data frame "Cases". So, my final output should be :

"Cases" Data Frame should have following:

  Date         Death       Cured     Samples      Positive
  15-04-2020    5             2        NA            NA
  16-04-2020    4             3        NA            NA
  17-04-2020    2             5        NA            NA
  18-04-2020    5             10       50            15
  19-04-2020    7             13       60            20
  20-04-2020    4             12       70            16
  21-04-2020    6             13       80            19
  22-04-2020    4             13       90            17

I have looked multiple answers on stack overflow but couldn't able to do the specific operation. How can we do it using dplyr package or normal if-else.

Martin Gal
  • 16,640
  • 5
  • 21
  • 39
sats
  • 153
  • 5
  • 14
  • You need to format your dates to be the same, e.g.: `test$Date = gsub("/", "-", df2$Date)` and then you can use: `dplyr::left_join(Cases, test, by = 'Date')` – Matt May 25 '20 at 14:05
  • I tried following: test$Date <- format(as.Date(test$Date, '%Y-%m-%d'), "%d/%m/%Y") dplyr::left_join(Cases, test, by = "Date") , but this is adding new columns with all values as NA. – sats May 25 '20 at 14:31
  • Also i am getting following warning: Column `Date` joining factor and character vector, coercing into character vector – sats May 25 '20 at 14:37
  • 1
    If you're getting all NA that is because the two columns don't match. As i mentioned above, they need to be the same. in your example you had two formats, dates seperated with `/` and `-`. If you use `gsub` to format this to be the same, then they should join. – Matt May 25 '20 at 14:52

0 Answers0