在R中如何根据两个日期之间的时间段组合数据帧?

时间:2016-06-29 23:52:00

标签: r dataframe merge

我有两个数据帧。 每天都有一个日期列。

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

另一列有两列日期试剂类型。

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

我需要将这两个数据帧组合在一起,这样我每天都会有一个reagent_types列。 2016-01-01到2016-01-31将是Reagent A.然后2016-02-01到2016-02-14会有Reagent B.所以就这样了。
非常感谢你提前。

2 个答案:

答案 0 :(得分:3)

您可以使用findInterval,假设第一个数据框为dateDf,第二个数据框为typeDf

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

数据

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")

答案 1 :(得分:0)

我们也可以使用<!DOCTYPE html> <html> <head> <title>ScatterDots! the StackOverFlow Edition</title> <script src="ScatterDots.js"></script> </head> <body onload='StartGame()'> <canvas id="GameMap" width="750" height="750" style="border:1px solid #000000"></canvas> </body> </html>

cut