我有一个巨大的数据集,其中的列如下所示(以及其他列)。5mln行和11列。
SYM
|
日期
|
小时
|
分钟
|
第二
|
A.
|
2020年10月1日
|
6.
|
10
|
1.
|
A.
|
2020年10月1日
|
6.
|
15
|
22
|
A.
|
2020年10月1日
|
7.
|
4.
|
23
|
A.
|
2020年10月2日
|
7.
|
23
|
23
|
B
|
2020年10月1日
|
6.
|
22
|
45
|
B
|
2020年10月1日
|
12
|
56
|
47
|
B
|
2020年10月2日
|
16
|
43
|
2.
|
C
|
2020年10月1日
|
6.
|
31
|
23
|
C
|
2020年10月2日
|
6.
|
41
|
24
|
C
|
2020年10月2日
|
7.
|
9
|
33
|
D
|
2020年10月1日
|
6.
|
2.
|
22
|
D
|
2020年10月2日
|
6.
|
4.
|
12
|
D
|
2020年10月3日
|
7.
|
54
|
12
|
D
|
2020年10月3日
|
8.
|
53
|
12
|
D
|
2020年10月3日
|
8.
|
55
|
12
|
D
|
2020年10月3日
|
9
|
4.
|
12
|
D
|
2020年10月3日
|
9
|
7.
|
24
|
我还有另一个数据集,它看起来是这样的:
日期
|
小时
|
分钟
|
第二
|
2020年10月1日
|
6.
|
10
|
1.
|
2020年10月1日
|
6.
|
22
|
45
|
2020年10月2日
|
16
|
43
|
2.
|
2020年10月2日
|
6.
|
41
|
24
|
2020年10月2日
|
7.
|
9
|
33
|
2020年10月3日
|
7.
|
54
|
12
|
2020年10月3日
|
8.
|
53
|
12
|
2020年10月3日
|
8.
|
55
|
12
|
2020年10月4日
|
9
|
4.
|
12
|
2020年10月4日
|
9
|
7.
|
24
|
让我们分别称之为df1和df2。
我想让df1看看df2,在日期、小时、分钟、秒匹配的地方放一个dumm=1。
然而,在df2(即引用)中,有一些引用不存在于df1中。
因此,我希望df1在最接近df2中显示的日期h,m,s之后插入一行,复制所有值,但创建一个与df2中所示值相等的d,h,m、s,并只给该行一个dummy=1。
示例:
df2具有04:14:08,而df1具有04:114:05或04:14:09。
如果发生这种情况:创建一个时间为04:14:08的新行,并为其提供04:14:05中存在的所有值,并仅为新行04:14:08dumm=1。
我怎么能这么做?
我尝试了以下操作:
df1<- dplyr::inner_join( df1
, df2
, by = c( "date") # only use date as a key
, suffix = c("", "_b")
) %>%
mutate(
datetime_a = ymd_hms( paste0( date, " "
, sprintf("%02d", hour), ":"
, sprintf("%02d", minute), ":"
, sprintf("%02d", second)
))
, datetime_b = ymd_hms( paste0( date, " "
, sprintf("%02d", hour_b), ":"
, sprintf("%02d", minute_b), ":"
, sprintf("%02d", second_b)
) )
, diff_seconds = abs(as.integer(difftime(datetime_a, datetime_b, units = "secs")))
) %>%
# Remove rows where the difference between datetime_a and datetime_b is
# greater than 3 seconds:
filter(diff_seconds <= 3 ) %>%
# Then add the dummy variable:
mutate(dummy = 1) %>%
# Remove any unnecessary columns:
select(date, sym, hour, minute, second,bidPrice.x,offerPrice.x,mid.x,lag.x,lagsym.x,ret.x, dummy) %>%
# Add the dummy column to A using a left_join:
dplyr::left_join(swd, ., by = c("date", "sym", "hour", "minute", "second")) %>%
# Rows without any matches have dummy = NA. Recode:
mutate(dummy = ifelse( is.na(dummy), yes = 0, no = dummy))
这是一个近似值,也就是说,观察+/-3秒的范围。然而,这给出了多个dumm=1,这对我来说并不好。