【问题标题】:Dividing by group按组划分
【发布时间】:2018-02-16 20:31:13
【问题描述】:

我有客户数据和他们购买产品的年份。

df <- data.frame(CustomerID    = c(1, 1, 1, 2, 2, 2), 
             Year = c(2012,2012,2013, 2014, 2015, 2016))

我想计算每个客户购买产品的平均时间。 我想要的结果是

_CustomerID____|__AVG per Year____ 
  1            | 1.5
  2            | 1

【问题讨论】:

    标签: r


    【解决方案1】:

    使用dplyr 你可以做到

    library(dplyr)
    
    df %>% 
      group_by(CustomerID, Year) %>% 
      summarise(count=n()) %>% 
      summarise(AvgPerYear=mean(count))
    

    【讨论】:

      【解决方案2】:

      您可以使用一些简单的dplyr 工具来做到这一点。在这里,您首先要group_byCustomerID,这意味着您正在对各个客户组执行后续步骤。然后,我们使用summarise 来获取您想要的值。从您的示例中,我将“每个客户购买产品的平均时间”解释为“取行数除以年数,包括两端”。

      df <- data.frame(CustomerID    = c(1, 1, 1, 2, 2, 2), 
                       Year = c(2012,2012,2013, 2014, 2015, 2016))
      library(dplyr)
      df %>%
        group_by(CustomerID) %>%
        summarise(yr_avg = n() / (max(Year) - min(Year) + 1))
      #> # A tibble: 2 x 2
      #>   CustomerID yr_avg
      #>        <dbl>  <dbl>
      #> 1       1.00   1.50
      #> 2       2.00   1.00
      

      reprex package (v0.2.0) 于 2018 年 2 月 16 日创建。

      【讨论】:

        【解决方案3】:

        使用baser:

        aggregate(Year~CustomerID,df,function(x)length(x)/length(unique(x)))
          CustomerID Year
        1          1  1.5
        2          2  1.0
        

        【讨论】:

          猜你喜欢
          • 2012-09-06
          • 1970-01-01
          • 1970-01-01
          • 2020-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-07
          相关资源
          最近更新 更多