假设这个数据集:
date exdate flag V1 V2
1996-01-04 1996-01-20 P 400000 -0.001181
1996-01-04 1996-01-20 C 400000 -0.004897
.............
1996-01-04 1996-01-20 P 530000 -0.005147
.............
1996-01-04 1996-01-20 P 535000 -0.005423
.............
1996-01-04 1996-01-20 C 545000 -0.007922
1996-01-04 1996-01-20 P 545000 -0.008389
我已按所需格式对数据进行排序,并且我只想提取同一组date
,exdate
和V1
中的行,但删除了单一观察组。请注意,有些组只包含一个观察,而不是C
和P
(在标志变量中),与第一个和最后一个组中的一样。
可以通过R中的包dplyr::filter
?
我试过这个:
data %>% group_by(date,exdate,V1) %>% filter(V1[flag=="P"]==V1[flag=="C"])
返回错误:
Error in filter_impl(.data, dots) : incorrect length (0), expecting: 1
目标是获得如下数据集:
date exdate flag V1 V2
1996-01-04 1996-01-20 P 400000 -0.001181
1996-01-04 1996-01-20 C 400000 -0.004897
.............
1996-01-04 1996-01-20 C 545000 -0.007922
1996-01-04 1996-01-20 P 545000 -0.008389
答案 0 :(得分:1)
data <- read.table(header = T, text = '
date exdate flag V1 V2
1996-01-04 1996-01-20 P 400000 -0.001181
1996-01-04 1996-01-20 C 400000 -0.004897
1996-01-04 1996-01-20 P 530000 -0.005147
1996-01-04 1996-01-20 P 535000 -0.005423
1996-01-04 1996-01-20 C 545000 -0.007922
1996-01-04 1996-01-20 P 545000 -0.008389
')
library(dplyr)
data %>%
group_by(date, exdate, V1) %>%
filter(n() == 2)