[英]Multiply column values in one data.frame by column in another data.frame on a condition in R
[英]Check R data.frame column for equal values in another column
我正在尋找以下問題的矢量化解決方案。 有些客戶一次可以擁有兩種不同的產品 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 進行分組。 但是后來我不知道如何在from_date
檢查to_date
是否具有相等的值。
您可以檢查以下所有條件:
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')
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.