R检查数据帧中的行对

ste*_*ejb 4 r

我有一个数据框,其中包含有关此类选项的信息

> chData
myIdx strike_price       date     exdate cp_flag strike_price    return
1 8355342       605000 1996-04-02 1996-05-18       P       605000  0.002340
2 8355433       605000 1996-04-02 1996-05-18       C       605000  0.002340
3 8356541       605000 1996-04-09 1996-05-18       P       605000 -0.003182
4 8356629       605000 1996-04-09 1996-05-18       C       605000 -0.003182
5 8358033       605000 1996-04-16 1996-05-18       P       605000  0.003907
6 8358119       605000 1996-04-16 1996-05-18       C       605000  0.003907
7 8359391       605000 1996-04-23 1996-05-18       P       605000  0.005695
Run Code Online (Sandbox Code Playgroud)

其中cp_flag表示某个选项是call或put.有什么方法可以确保每个日期都有一个调用和一个put,并删除不存在的行?我可以用for循环来做,但是有更聪明的方法吗?

wch*_*wch 10

获取具有P的日期和具有C的日期,并使用相交来查找具有两者的日期.

keep_dates <- with(x, intersect(date[cp_flag=='P'], date[cp_flag=='C']) )
# "1996-04-02" "1996-04-09" "1996-04-16"
Run Code Online (Sandbox Code Playgroud)

仅保留keep_dates中出现日期的行.

x[ x$date %in% keep_dates, ]
#   myIdx strike_price       date     exdate cp_flag strike_price.1
# 8355342       605000 1996-04-02 1996-05-18       P         605000
# 8355433       605000 1996-04-02 1996-05-18       C         605000
# 8356541       605000 1996-04-09 1996-05-18       P         605000
# 8356629       605000 1996-04-09 1996-05-18       C         605000
# 8358033       605000 1996-04-16 1996-05-18       P         605000
# 8358119       605000 1996-04-16 1996-05-18       C         605000
Run Code Online (Sandbox Code Playgroud)