考虑以下数据集:
| 公司名称 | 年 | 顾客 |
|---|---|---|
| A公司 | 2018年 | 100 |
| B公司 | 2018年 | 120 |
| C公司 | 2018年 | 150 |
| A公司 | 2019年 | 120 |
| B公司 | 2019年 | 180 |
| C公司 | 2019年 | 80 |
| A公司 | 2020年 | 200 |
| B公司 | 2020年 | 500 |
| C公司 | 2020年 | 140 |
我想做的是衡量客户未来的回报。因此,我需要在新列中包含明年的客户数量。像这样的东西:
| 公司名称 | 年 | 顾客 | 明年的客户 |
|---|---|---|---|
| A公司 | 2018年 | 100 | 120 |
| B公司 | 2018年 | 120 | 180 |
| C公司 | 2018年 | 150 | 80 |
| A公司 | 2019年 | 120 | 200 |
| B公司 | 2019年 | 180 | 500 |
| C公司 | 2019年 | 80 | 140 |
| A公司 | 2020年 | 200 | 不适用 |
| B公司 | 2020年 | 500 | 不适用 |
| C公司 | 2020年 | 140 | 不适用 |
有人知道如何做到这一点吗?
lead您可以像下面的代码一样使用:
library(dplyr)\ndf %>%\n group_by(Company) %>%\n mutate(customers_next_year = lead(Customers)) %>%\n ungroup()\nRun Code Online (Sandbox Code Playgroud)\n输出:
\n# A tibble: 9 \xc3\x97 4\n# Groups: Company [3]\n Company Year Customers customers_next_year\n <chr> <dbl> <dbl> <dbl>\n1 A 2018 100 120\n2 B 2018 120 180\n3 C 2018 150 80\n4 A 2019 120 200\n5 B 2019 180 500\n6 C 2019 80 140\n7 A 2020 200 NA\n8 B 2020 500 NA\n9 C 2020 140 NA\nRun Code Online (Sandbox Code Playgroud)\ndf <- data.frame(Company = rep(c("A", "B", "C"), 3),\n Year = c(2018, 2018, 2018, 2019, 2019, 2019, 2020, 2020, 2020),\n Customers = c(100,120,150,120,180,80,200,500,140))\nRun Code Online (Sandbox Code Playgroud)\n