【问题标题】:Is there a way to merge two dataframes by a mathematical operation in R?有没有办法通过 R 中的数学运算合并两个数据帧?
【发布时间】:2020-04-08 03:50:29
【问题描述】:

我正在做一个小型 R 项目。

给定两个不同长度的数据帧:

df1 = data.frame(Plane.Id = c(19924519, 19924321, 19992436, 19924119, 19924208, 19924330), 
                 Block.ID = c(090LC, 090LC, 001UG, 002LM, 001OI, 001UG), 
                 Hour1 = c(0.02222222, 0.02222222, 15.07222, 15.44444, 6.652778, 3.286111))

df2 = data.frame(Block.Id = c(090LC, 001UG, 001UG, 002LM, 001OI), 
                 Sector.ID = c(BIRDFIS, UKOVS, LLLLALL, EBBUEHS, LEBLDDN), 
                 Hour_In = c(0.000000, 0.000000, 13.000000, 0.000000, 0.000000), 
                 Hour_Out = c(23.50000, 13.000000, 23.50000, 23.50000, 23.50000))

不同的 Sector.ID 根据一天中的时间分配给同一个 Block.ID。

是否可以按照以下条件将它们合并到单个数据帧中?:

  • 如果两个数据帧中的 Block.ID 列值相同
  • 如果 df1 的 Hour1 值介于 df2 的 Hour_In 和 Hour_Out 之间(Hour_in

我正在寻找的是一个长度为 df1 的数据帧,其中包含数据 Plane.ID、Block.ID 和 Sector.ID。像这样的东西(我不知道如何在这里建一个表格,所以我上传了一张带有表格的图片):

df_final

我尝试过使用 rbind、left_join、merge、cbind 并没有什么好的结果。我什至尝试使用循环来执行此操作,但不是一个好主意。

【问题讨论】:

  • 一目了然,听起来你想要一个来自 data.table 的非 equi 连接

标签: r dataframe merge conditional-statements


【解决方案1】:

这是使用data.table 的替代解决方案:

library(data.table)

setDT(df1)
setDT(df2)

df1[df2, on = .(Block.ID, Hour1 >= Hour_In, Hour1 <= Hour_Out), .(Plane.Id, Block.ID, Sector.ID)]

输出

   Plane.Id Block.ID Sector.ID
1: 19924519    090LC   BIRDFIS
2: 19924321    090LC   BIRDFIS
3: 19924330    001UG     UKOVS
4: 19992436    001UG   LLLLALL
5: 19924119    002LM   EBBUEHS
6: 19924208    001OI   LEBLDDN

【讨论】:

    【解决方案2】:

    如何使用dplyr对“Block_id”进行内部连接并按“Hour1”进行过滤?

    df1 = 
      data.frame(
        Plane.Id = c(19924519, 19924321, 19992436, 19924119, 19924208, 19924330), 
        Block.ID = c("090LC", "090LC", "001UG", "002LM", "001OI", "001UG"), 
        Hour1    = c(0.02222222, 0.02222222, 15.07222, 15.44444, 6.652778, 3.286111)
      )
    
    df2 = data.frame(
      Block.ID = c("090LC", "001UG", "001UG", "002LM", "001OI"), 
      Sector.ID = c("BIRDFIS", "UKOVS", "LLLLALL", "EBBUEHS", "LEBLDDN"), 
      Hour_In = c(0.000000, 0.000000, 13.000000, 0.000000, 0.000000), 
      Hour_Out = c(23.50000, 13.000000, 23.50000, 23.50000, 23.50000)
    )
    
    dplyr::inner_join(df1, df2, by="Block.ID") %>%
    dplyr::filter(Hour1 > Hour_In & Hour1 < Hour_Out)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 2021-08-20
      • 2021-11-20
      • 2014-04-14
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多