如何匹配 R 中子集的最小值,然后进行查找?

How do I match the minimum of a subset in R, then do a lookup?

输入

我有按客户和订单细分的数据,例如

Customer_ID Order_Source Date_of_order
1           Online       03/01/2017
1           Phone        02/01/2017
1           Store        01/01/2017
2           Fax          02/01/2017
2           Phone        01/01/2017

输出

我的目标是:

  1. 找出每个客户的第一个订单日期(最小)。让我们假设每个客户都有一个唯一的第一个订单日期(我也有时间,以防日期并列)
  2. 然后查找使用的第一个订单来源
  3. 最后,使用此信息创建一个新列,即

Customer_ID Order_Source Date_of_order   First_Order_Source
    1           Online       03/01/2017  Store
    1           Phone        02/01/2017  Store
    1           Store        01/01/2017  Store
    2           Fax          02/01/2017  Phone
    2           Phone        01/01/2017  Phone

我的问题是,如何从这样的子集的最小值中查找?

我们可以在按'Customer_ID'分组后,将'Date_of_order'转换为Dateclass,得到最小值'Date'的索引(which.min), 得到'Order_Source'和mutate对应的值新建一列

library(dplyr)
df1 %>% 
    group_by(Customer_ID) %>%
    mutate(First_Order_Source = Order_Source[which.min(as.Date(Date_of_order, "%m/%d/%Y"))])
#   Customer_ID Order_Source Date_of_order First_Order_Source    
#        <int>        <chr>         <chr>              <chr>
#1           1       Online    03/01/2017              Store
#2           1        Phone    02/01/2017              Store
#3           1        Store    01/01/2017              Store
#4           2          Fax    02/01/2017              Phone
#5           2        Phone    01/01/2017              Phone

这是使用 ave 按客户分组的基本 R 方法:

df <- within(df, {
  Date_of_order <- as.Date(Date_of_order, format = "%d/%m/%Y")
  first_order <- Order_Source[ave(as.integer(Date_of_order), Customer_ID, FUN = which.min)]
})