【问题标题】:Mutate between dates from external lookup table [duplicate]在来自外部查找表的日期之间变化[重复]
【发布时间】:2020-07-15 09:55:48
【问题描述】:

我想通过查找外部“日期查找表”来改变包含日期列表的 tibble

date_lookup<-tibble(start = lubridate::dmy("01012020", "01022020"),
           end = lubridate::dmy("31012020", "28022020"),
           id = c(1, 2))

df<-tibble(record = c("A", "B"),
           date = lubridate::dmy("15022020", "03012020"))

如果df 中的日期介于date_lookup 中的开始日期或结束日期之间,我想从date_lookup 中提取适当的id

我尝试了以下方法:

df %>% rowwise() %>% 
  mutate(id = ifelse(between(date, date_lookup$start, date_lookup$end), date_lookup$id, NA))

但如您所见,df 中的第一行显示为 NA(它应该显示数字 2)。

预期输出:

# A tibble: 2 x 3
# Rowwise: 
  record date          id
  <chr>  <date>     <dbl>
1 A      2020-02-15     2
2 B      2020-01-03     1

dplyr 解决方案更可取。

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    你可以在这里使用fuzzyjoin

    fuzzyjoin::fuzzy_inner_join(df, date_lookup, 
               by = c('date' = 'start', 'date' = 'end'), match_fun = list(`>=`, `<=`))
    
    # A tibble: 2 x 5
    #  record date       start      end           id
    #  <chr>  <date>     <date>     <date>     <dbl>
    #1 A      2020-02-15 2020-02-01 2020-02-28     2
    #2 B      2020-01-03 2020-01-01 2020-01-31     1
    

    使用tidyverse 函数:

    tidyr::crossing(df, date_lookup) %>% dplyr::filter(date >= start, date <= end)
    

    【讨论】:

      【解决方案2】:

      这是一个 方法,它使用非 equi 连接,然后将值分配给原始 data.frame。

      library(data.table)
      library(tibble)
      date_lookup<-tibble(start = lubridate::dmy("01012020", "01022020"),
                          end = lubridate::dmy("31012020", "28022020"),
                          id = c(1, 2))
      
      df<-tibble(record = c("A", "B"),
                 date = lubridate::dmy("15022020", "03012020"))
      
      setDT(date_lookup)
      setDT(df)
      
      df[date_lookup,
         on = .(date >= start,
                date <= end),
         id := id]
      
      df
      #>    record       date id
      #> 1:      A 2020-02-15  2
      #> 2:      B 2020-01-03  1
      

      【讨论】:

        猜你喜欢
        • 2011-09-29
        • 1970-01-01
        • 1970-01-01
        • 2016-12-07
        • 1970-01-01
        • 2016-07-11
        • 1970-01-01
        • 1970-01-01
        • 2012-09-24
        相关资源
        最近更新 更多