【问题标题】:In R how to combine dataframes based on period between two dates?在 R 中,如何根据两个日期之间的时间段组合数据帧?
【发布时间】:2016-06-29 23:52:00
【问题描述】:

我有两个数据框。 一个包含每天的日期列。

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 将是试剂 A。然后 2016-02-01 到 2016-02-14 将有试剂 B。依此类推。
非常感谢您。

【问题讨论】:

标签: r dataframe merge


【解决方案1】:

你可以使用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")

【讨论】:

    【解决方案2】:

    我们也可以使用cut

    dateDf$ReagentType <- typeDf$ReagentType[as.numeric(cut(dateDf$Date, 
                                                     breaks = typeDf$Date))]
    

    【讨论】:

      猜你喜欢
      • 2020-04-20
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 2022-11-02
      • 1970-01-01
      • 2020-01-26
      相关资源
      最近更新 更多