【问题标题】:Check R data.frame column for equal values in another column检查 R data.frame 列中另一列中的相等值
【发布时间】:2020-03-29 23:28:14
【问题描述】:

我正在寻找以下问题的矢量化解决方案。有些客户可以同时拥有两种不同的产品 x 或 y 中的一种。我想为同一客户识别产品 x 后跟产品 y 的所有行。在这种情况下,产品 x 的 to_date 将与产品 y 的 from_date 相同。这是一个例子:

customerid = c(rep(1,2),rep(2,3))
product = c("x", "y", "x", "x", "y")
from_date = as.Date(c("2000-01-01", "2000-06-07","2001-02-01","2005-01-01","2005-11-01"))
to_date = as.Date(c("2000-06-07", "2000-10-31","2002-04-01","2005-11-01","2006-01-01"))

data.frame(customerid, product, from_date, to_date)

      customerid product  from_date    to_date
1          1       x 2000-01-01 2000-06-07
2          1       y 2000-06-07 2000-10-31
3          2       x 2001-02-01 2002-04-01
4          2       x 2005-01-01 2005-11-01
5          2       y 2005-11-01 2006-01-01

所需的输出如下所示:

  customerid product  from_date    to_date followed_by_y
1          1       x 2000-01-01 2000-06-07             yes
2          1       y 2000-06-07 2000-10-31             no
3          2       x 2001-02-01 2002-04-01             no
4          2       x 2005-01-01 2005-11-01             yes
5          2       y 2005-11-01 2006-01-01             no

到目前为止,我的方法是使用 dplyr 按costumerid 对 data.frame 进行分组。但是后来我不知道如何检查to_datefrom_date 中的相等值。

【问题讨论】:

    标签: r


    【解决方案1】:

    您可以检查以下所有条件:

    library(dplyr)
    
    df %>%
      group_by(customerid) %>%
      mutate(followed_by_y = c('no', 'yes')[(product == 'x' &
                                             lead(product) == 'y' &
                                             to_date == lead(from_date)) + 1])
    

    输出:

    # A tibble: 5 x 5
    # Groups:   customerid [2]
      customerid product from_date  to_date    followed_by_y
           <dbl> <fct>   <date>     <date>     <chr>        
    1          1 x       2000-01-01 2000-06-07 yes          
    2          1 y       2000-06-07 2000-10-31 no           
    3          2 x       2001-02-01 2002-04-01 no           
    4          2 x       2005-01-01 2005-11-01 yes          
    5          2 y       2005-11-01 2006-01-01 no   
    

    注意,这与说的基本相同:

    library(dplyr)
    
    df %>%
      group_by(customerid) %>%
      mutate(followed_by_y = case_when(
        product == 'x' & lead(product) == 'y' & to_date == lead(from_date) ~ 'yes',
        TRUE ~ 'no')
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-27
      • 1970-01-01
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2015-02-01
      • 2022-06-14
      相关资源
      最近更新 更多