R Studio - 将 df 的二进制列映射到另一个的行详细信息并匹配?

R Studio - Map binary columns of df to row details of another and match?

我在下面有这两个数据集 - “数据”是参加锦标赛的人员列表,二进制列表示他们正在参加哪些比赛,“tourn_details”表示比赛日期这些比赛发生在。

name <- c('Sarah', 'Josh', 'Ben')
tourn1 <- c(1, 1, 0)
tourn2 <- c(0, 1, 1)
tourn3 <- c(1, 0, 0)
data <- data.frame(name, tourn1, tourn2, tourn3)

tourns <- c("tourn1", "tourn2", "tourn3")
dates <- c("2020-01-01, 2020-01-02", "2020-01-01", "2020-01-02, 2020-01-03")
tourn_details <- data.frame(tourns, dates)

我现在正在尝试向“数据”添加一个名为“比赛日期”的列,该列将列出参赛者参加比赛的所有日期。例如,Sarah 正在参加 tourn1 和 tourn3 -使用 tourn_details,这意味着她将在 1 月 1 日、1 月 2 日(第 1 场比赛)和 1 月 2 日、1 月 3 日(第 3 场比赛)比赛。她的“比赛日期”应该是“2020-01-01、2020-01-02、2020-01-02、2020-01-03”(注意重复的日期)。

最后一部分是我想添加一个列,显示每个玩家从某个日期开始玩了多少场比赛。假设我将日期设置为 1 月 1 日 - 我想知道每位玩家即将进行多少场比赛。对于 Sarah,在 1 月 1 日,这应该等于 3(因为她在 1 月 2 日打了两场比赛,在 1 月 3 日打了一场)。

提前致谢,如果我可以提供更多详细信息,请告诉我!

library(tidyverse)

data %>% 
  dplyr::mutate(across(starts_with("tourn"), ~ ifelse(.x, cur_column(), NA))) %>% 
  tidyr::unite(tourn, starts_with("tourn"), sep = ", ", na.rm = T) %>%
  dplyr::rowwise() %>%
  dplyr::mutate(playing_dates = tourn_details[str_detect(tourn, tourn_details$tourns), "dates"] %>%
                  paste(collapse = ", "),
                upcoming = sum(as.Date(str_split(playing_dates, ", ")[[1]]) %in%
                                 seq(as.Date("2020-01-01"), length.out = 7, by = 1))) %>% 
  dplyr::ungroup()

输出

  name  tourn          playing_dates                                  upcoming
  <chr> <chr>          <chr>                                             <int>
1 Sarah tourn1, tourn3 2020-01-01, 2020-01-02, 2020-01-02, 2020-01-03        4
2 Josh  tourn1, tourn2 2020-01-01, 2020-01-02, 2020-01-01                    3
3 Ben   tourn2         2020-01-01                                            1   

您可以将 as.Date("2020-01-01") 调整为您想要的任何开始日期。它将看起来 7 天。这通过创建一个日期序列 (seq) 从您的开始日期一次一天 (by = 1) 直到序列有七个元素长 (length.out = 7).