我正在尝试根据另一列中的值(在这种情况下为日期)比较两个因素。如果它们不匹配,我想删除该行。
示例:
>head(data)
light date
1 0 20190314
2 0 20190317
3 1 20190314
4 0 20190318
5 1 20190316
6 1 20190318
7 1 20190314
所以我希望结果是:
>head(data)
light date
1 0 20190314
2 1 20190314
3 0 20190318
4 1 20190318
5 1 20190314
提前感谢
这里是一种解决方法。
输入
tribble(~light, ~date,
"0","20190314",
"0","20190317",
"1","20190314",
"0","20190318",
"1","20190316",
"1","20190318",
"1","20190314"
) ->d
代码
library(dplyr)
d %>% group_by(date) %>%
mutate(is_keep = if_else("0" %in% light & "1" %in% light, 1,0)) %>%
filter(is_keep==1) %>% select(-is_keep) %>% ungroup()
输出
light date
<chr> <chr>
1 0 20190314
2 1 20190314
3 0 20190318
4 1 20190318
5 1 20190314
您可以通过以下方法来检查数据框,方法是检查某个值是否在其他数据框中的特定列中:
data <- data %>%
filter(date %in% unique(other_df$reference_column))