dplyr グループごとに指数化
グループごとにある時点における数値をもとにした指数化を行いたい。
何らかの売上データが時系列であるとする。
> library(tidyverse) > library(lubridate) > > sales_tbl <- tibble( + sales_date = rep(seq(ymd("2020-05-01"), ymd("2020-05-31"), by = "1 day"), 3), + category = c(rep("food", 31), rep("book", 31), rep("tool", 31)), + sales_cnt = rpois(31 * 3, 10) + ) > > sales_tbl # A tibble: 93 x 3 sales_date category sales_cnt <date> <chr> <int> 1 2020-05-01 food 11 2 2020-05-02 food 8 3 2020-05-03 food 8 4 2020-05-04 food 15 5 2020-05-05 food 12 6 2020-05-06 food 10 7 2020-05-07 food 6 8 2020-05-08 food 10 9 2020-05-09 food 15 10 2020-05-10 food 11 # … with 83 more rows
特定の日付の売上を1として、グループごとにその後の売上を指数化する。
> sales_index_tbl <- sales_tbl %>% + group_by(category) %>% + mutate(sales_index = sales_cnt / sales_cnt[sales_date == ymd("2020-05-01")]) > > sales_index_tbl %>% + ggplot(aes(x = sales_date, y = sales_index)) + + geom_line(aes(colour = category), size = 2) + + scale_x_date(breaks = "1 week", minor_breaks = "1 day") + + theme(legend.position = "top")
それぞれのグループごとに5月1日時点を1として、指数化されることがわかる。
[]
による条件絞り込みをmutateの中で効かせることができる。