我想根据reports_example数据框架的月份列和Park列(也在下面)从AC_example数据框架中删除一些行(参见下面)。我希望reports_example数据框架的第一个月要么是相同的,要么是在AC_example数据框架之后。
下面是所讨论的两个数据框架的子集:
reports_example <- read.table(header=TRUE, text="
Month Park
2019-12-01 Aspen_Heights
2020-02-01 Aspen_Heights
2020-05-01 Aspen_Heights
2021-06-01 Aspen_Heights
2019-11-01 Auburn_Bay
2020-03-01 Auburn_Bay
")
AC_example <- read.table(header=TRUE, text="
Month Park
2020-05-01 Aspen_Heights
2020-06-01 Aspen_Heights
2020-07-01 Aspen_Heights
2021-04-01 Aspen_Heights
2020-03-01 Auburn_Bay
2021-03-01 Auburn_Bay
")我希望最后报告数据框架如下所示:
reports_final_example <- read.table(header=TRUE, text="
Month Park
2020-05-01 Aspen_Heights
2021-06-01 Aspen_Heights
2020-03-01 Auburn_Bay
")任何帮助都将不胜感激!
发布于 2021-09-18 14:22:41
另一种方法是使用fuzzyjoin包。“半”连接将包括第一个data.frame中的行,在第二个data.frame中可以找到匹配的行。连接将在Park和Month上匹配(第一个data.frame的Month在第二个data.frame之后)。
library(fuzzyjoin)
fuzzy_semi_join(
reports_example,
AC_example,
by = c("Park" = "Park", "Month" = "Month"),
match_fun = c(`==`, `>=`)
)输出
Month Park
3 2020-05-01 Aspen_Heights
4 2021-06-01 Aspen_Heights
6 2020-03-01 Auburn_Bay发布于 2021-09-17 18:26:57
使用tidyverse
reports_example %>%
mutate(Month_example = as.Date(Month)) %>%
left_join(AC_example %>% mutate(Month_AC = as.Date(Month)), by = 'Park') %>%
filter(Month_example >= Month_AC) %>%
select(Park, Month_example, Month_AC) %>%
distinct(Park, Month_example)在以下方面的成果:
Park Month_example
1 Aspen_Heights 2020-05-01
2 Aspen_Heights 2021-06-01
3 Auburn_Bay 2020-03-01https://stackoverflow.com/questions/69227827
复制相似问题