如何解决在R中转置DataFrame:将一行作为列,另一列聚合为行
为了更好地解释我的问题,我准备了以下看起来与原始数据集相似的示例数据:
library(zoo)
sample_data <- data.frame(User = c("customer1","customer2","customer3","customer4","customer5","customer1","customer5"),Cohort = as.yearmon(c("2020-03-01","2020-02-17","2020-04-10","2020-02-01","2020-03-01","2020-04-30"),"%Y-%m-%d"),Purchase_month = as.yearmon(c("2020-03-01","2020-07-05","2020-03-05","2020-06-11","2020-03-07","2020-11-01","2020-11-04","2020-06-30"),Revenue = c(25,34,20,50,75,80,100,76,39,10,90))
如您所见,我有一个购买数据,其中有一个列指示客户,一个列有他们所属的同类群组(他们下第一笔订单的月份),另一列可以找到他们的购买日期,另一个列有他们的每次购买支出。
我想做的就是更改表格,以在每列中显示每行同类和每个月每月收入。 结果基本上应该如下所示
Cohort | Feb 2020 | Mar 2020 | Apr 2020 | May 2020 | Jun 2020 | Jul 2020 | Aug 2020 | Sep 2020 | Oct 2020 | Nov 2020 | Dec 2020
Feb 2020 | 84 | 139 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0
Mar 2020 | 0 | 25 | 0 | 0 | 0 | 80 | 0 | 0 | 0 | 20 | 0
Apr 2020 | 0 | 0 | 95 | 0 | 169 | 0 | 0 | 0 | 0 | 10 | 0
谢谢!
Ps:也许标题不太合适,但我不知道如何调用表格的这种转换。
解决方法
我们可以删除User
列并执行sum
个值中的Revenue
。
library(dplyr)
library(tidyr)
sample_data %>%
select(-User) %>%
pivot_wider(names_from = Purchase_month,values_from = Revenue,values_fill = 0,values_fn = sum)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。