R 检查数据帧中的行对

标签 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

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

最佳答案

获取具有 P 的日期和具有 C 的日期,并使用 intersect 查找同时具有两者的日期。

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

仅保留在 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

关于R 检查数据帧中的行对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3420950/

相关文章:

r - R 中的选择性数据集成

r - 仅当 R 中存在列时 unnest_wider

list - 使用snowfall::sfLapply 时正在处理哪个列表元素?

r - R Studio 中的 "Index Match"(多列)

r - 在 R 中更改数据帧结构

r - 测试向量是否包含给定元素

R - 分别在 3d 中绘制两个二元法线及其轮廓

r - 如何修复 "Subscript out of bounds error"

r - Rmd 中出现 "long vectors not supported yet"错误,但 R 脚本中没有错误

r - 当数据不包含必要的值时如何忽略代码?