R语言 计算社区的年累计销售额,直至首次销售后三年

dwbf0jvd  于 2023-02-20  发布在  其他
关注(0)|答案(1)|浏览(97)

对于这个问题,我需要计算每个街区的季度累计销售额。棘手的是,我只有一个表,其中每行对应一个唯一的人,一列包含'销售额'和'销售日期',所以需要创建年份,因为有些年份可能没有销售额。
另一个要求是,只有在该地区首次销售后三年内的销售才能被考虑。我的数据框架如下所示:

dat <- tibble(
  Person = c(1, 2, 3, 4, 5, 6),
  Neighbourhood = c("XYZ", "XYZ", "XYZ", "XYZ", "ABC", "ABC"),
  Date_of_sale =  structure(c(17987, NA, 19275, 17564, 18052, NA), class = "Date"),
  Sale = c(1, 0, 1, 1, 1, 0)
)
dat
#> # A tibble: 6 × 4
#>   Person Neighbourhood Date_of_sale  Sale
#>    <dbl> <chr>         <date>       <dbl>
#> 1      1 XYZ           2019-04-01       1
#> 2      2 XYZ           NA               0
#> 3      3 XYZ           2022-10-10       1
#> 4      4 XYZ           2018-02-02       1
#> 5      5 ABC           2019-06-05       1
#> 6      6 ABC           NA               0

所需的输出如下所示:
| 邻里|年份|累计销量|
| - ------|- ------|- ------|
| XYZ|第1年|1个|
| XYZ|第二年|第二章|
| XYZ|第三年|第二章|
| 美国广播公司|第1年|1个|
| 美国广播公司|第二年|1个|
| 美国广播公司|第三年|1个|

b4lqfgs4

b4lqfgs41#

在这类问题中精确地计算闰年是R中的一件痛苦的事情。因此,我用365.25天来近似一年的长度。请查看评论中对步骤的解释。

library(tidyverse)
library(lubridate)

dat <- tibble(Person = c(1, 2, 3, 4, 5, 6),  Neighbourhood = c("XYZ", "XYZ", "XYZ", "XYZ", "ABC", "ABC"),  Date_of_sale =  structure(c(17987, NA, 19275, 17564, 18052, NA), class = "Date"),  Sale = c(1, 0, 1, 1, 1, 0))

sol <- dat |> 
  filter(Sale == 1) |> # keep only persons with sales
  arrange(Neighbourhood, Date_of_sale) |>
  group_by(Neighbourhood) |> 
  mutate(year = ((Date_of_sale - min(Date_of_sale) + 1)/365.25) |> # bring time diff to year level
          unclass() |> 
          ceiling() # round up to full year
         ) |> 
  group_by(Neighbourhood, year) |> 
  summarize(sales = sum(Sale)) |> 
  ungroup() |> 
  complete(Neighbourhood, year = 1:3, fill = list(sales = 0)) |> # Add year without sales
  filter(year <= 3) |> # Remove years greater than 3
  group_by(Neighbourhood) |> 
  mutate(cum_sales = cumsum(sales)) |>  # Cumulate sales across years
  ungroup()

sol
#> # A tibble: 6 × 4
#>   Neighbourhood  year sales cum_sales
#>   <chr>         <dbl> <dbl>     <dbl>
#> 1 ABC               1     1         1
#> 2 ABC               2     0         1
#> 3 ABC               3     0         1
#> 4 XYZ               1     1         1
#> 5 XYZ               2     1         2
#> 6 XYZ               3     0         2

相关问题