0

I have two dataframes. One with dates column with every day.

seq(as.Date("2016/1/1"), as.Date("2016/3/1"), by = "day")

The other with two columns of dates reagent_type.

    2016-01-01 A
2016-02-01 B
2016-02-15 A
2016-03-30 B

I need to combine these two dataframes so I would have a reagent_types column for everyday. 2016-01-01 to 2016-01-31 would be Reagent A. Then 2016-02-01 to 2016-02-14 would have Reagent B. So on so forth.
Thank you very much in advance.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
zodavaan
  • 3
  • 2
  • I just did this earlier today using this question http://stackoverflow.com/questions/23095896/merging-two-dataframes-on-a-date-range-in-r – Benjamin Jun 30 '16 at 02:55

2 Answers2

3

You can use findInterval, assuming the first data frame is dateDf and the second one is typeDf:

dateDf$ReagentType <- typeDf$ReagentType[findInterval(dateDf$Date, typeDf$Date)]

Data:

dput(dateDf)
structure(list(Date = structure(c(16801, 16802, 16803, 16804, 
16805, 16806, 16807, 16808, 16809, 16810, 16811, 16812, 16813, 
16814, 16815, 16816, 16817, 16818, 16819, 16820, 16821, 16822, 
16823, 16824, 16825, 16826, 16827, 16828, 16829, 16830, 16831, 
16832, 16833, 16834, 16835, 16836, 16837, 16838, 16839, 16840, 
16841, 16842, 16843, 16844, 16845, 16846, 16847, 16848, 16849, 
16850, 16851, 16852, 16853, 16854, 16855, 16856, 16857, 16858, 
16859, 16860, 16861), class = "Date"), ReagentType = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("A", 
"B"), class = "factor")), .Names = c("Date", "ReagentType"), row.names = c(NA, 
-61L), class = "data.frame")

dput(typeDf)
structure(list(Date = structure(c(16801, 16832, 16846, 16890), class = "Date"), 
    ReagentType = structure(c(1L, 2L, 1L, 2L), .Label = c("A", 
    "B"), class = "factor")), .Names = c("Date", "ReagentType"
), row.names = c(NA, -4L), class = "data.frame")
Psidom
  • 209,562
  • 33
  • 339
  • 356
0

We can also use cut

dateDf$ReagentType <- typeDf$ReagentType[as.numeric(cut(dateDf$Date, 
                                                 breaks = typeDf$Date))]
akrun
  • 874,273
  • 37
  • 540
  • 662