如果 x 的时间戳在 y 的时间间隔内,则合并两个数据帧 [英] Merge two dataframes if timestamp of x is within time interval of y

查看:21
本文介绍了如果 x 的时间戳在 y 的时间间隔内,则合并两个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法解决此问题.我有两个数据框.DF1 和 DF2.如果 DF1 中的时间戳在 DF2 中指定的时间间隔内,我想将 DF2 的列合并到 DF1.这是两个数据框的示例:

I cannot get a solution to this problem. I have two dataframes. DF1 and DF2. I would like to merge the columns of DF2 to DF1 if the timestamp in DF1 is within the time interval specified in DF2. Here is an example of the two dataframes:

DF1 <- structure(list(Airspeed = c(582L, 478L, 524L), Outbound.Track = c(119L, 78L,134L), Rem.Ground.Dist = c(369L, 119L, 196L), Timestamp=structure(c(1451636817.52577, 1451638203.76569, 1451637753.43511),class = c("POSIXct", "POSIXt"), tzone = "")), .Names =c("Airspeed", "Outbound.Track","Rem.Ground.Dist", "Timestamp"), row.names =c(1L, 12L, 7L), class = c("data.table", "data.frame"))

DF2 <- structure(list(Temperature = c(-18.5, -60, -35), Wind_Direction = c("324", "335", "313"), Wind_Speed = c("032", "041", "056"), onebef =structure(c(1451629620, 1451634660, 1451637000), class = c("POSIXct", "POSIXt"), tzone = ""), oneaft = structure(c(1451636820, 1451641860, 1451644200), class =c("POSIXct", "POSIXt"))), .Names = c("Temperature", "Wind_Direction", "Wind_Speed","onebef", "oneaft"), row.names = c(1358L, 1654L, 2068L), class = "data.frame")

head(DF1)
head(DF2)

我想将 DF1 与 DF2 合并.因此,如果匹配(DF1 的时间戳在任何 DF2 的时间间隔内),则应将 DF2 的值(Wind_Speed、Wind_Direction、Temperature)添加到 DF1.

I want to merge DF1 with DF2. So if there is a match (timestamp of DF1 is within time interval of any DF2), the values of DF2 (Wind_Speed, Wind_Direction, Temperature) should be added to DF1.

我面临的两个问题:

  1. 如何进行匹配/合并?我的数据框很大(DF1 和 DF2 中有 7000 行)

  1. How to do the match/merge? My dataframe is quite large (7000 rows in DF1 and DF2)

如果有多个匹配项,如何确保 DF1 的行是重复的?

How to ensure that rows of DF1 are duplicated if there are several matches?

我期待您的帮助!谢谢

推荐答案

你可以使用 sqldf:

You could use sqldf:

library(sqldf)
df<-sqldf('select d1.*,d2.*
           from DF1 d1
           left join DF2 d2
             on d1.Timestamp >= d2.onebef
               AND d1.Timestamp <= d2.oneaft
          ')
df

这篇关于如果 x 的时间戳在 y 的时间间隔内,则合并两个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆