【问题标题】:Add the years to the column and summarize the value in R将年份添加到列中并总结 R 中的值
【发布时间】:2020-05-05 12:12:51
【问题描述】:

我有一个如下的数据框

cust start-dt    end-dt      item item_type sales cost trans-dat
A    07-01-2019  07-01-2020  AA   xxxxxxxxx 1500  1400 08-01-2019
A    07-01-2019  07-01-2020  AA   xxxxxxxxx 2000  1600 09-01-2019
A    07-01-2019  07-01-2020  AA   xxxxxxxxx 2500  1000 07-12-2019
A    07-01-2019  07-01-2020  AA   xxxxxxxxx 1600  1300 05-01-2020
A    07-01-2019  07-01-2020  AA   xxxxxxxxx 2400  1700 02-01-2020
A    07-01-2019  07-01-2020  AA   xxxxxxxxx 2200  1300 04-01-2020

我需要转换为按年计算的数据,如下所示。 基于客户和他们每年购买的物品

cust start-dt    end-dt      item item_type  year sales cost
A    07-01-2019  07-01-2020  AA   xxxxxxxxx  2019 6000  4000
A    07-01-2019  07-01-2020  AA   xxxxxxxxx  2020 6200  4300

我尝试了熔化和铸造,但熔化不会创建新的列/行。

这个数据只是一个例子。我有多个客户和每个客户的多个项目,每个客户的开始和结束也不同。

请指导我如何解决这个问题。

【问题讨论】:

  • year 列是start-dtend-dttrans-dat 的年份吗?您想总结salescost 列吗?通过对它们求和?
  • 年份列是 start-dt 和 end-dt 之间的年份。将其视为客户的会员资格。但是销售额和成本是根据交易日期的交易日期相加的。 trans-dt 总是在 start-dt 和 end-dt 之间。

标签: r


【解决方案1】:

看起来结果中的year 来自trans-dt 列。因此,您需要提取那一年并进行分组求和。这是一个dplyr 方法:

library(dplyr)
df %>% 
  mutate(year = as.integer(substr(`trans-dt`, 7, 10))) %>% # chars 7 to 10 as the year
  group_by(cust, `start-dt`, `end-dt`, item, item_type, year) %>%
  summarize(sales = sum(sales), cost = sum(cost))

请参阅FAQ on summing by group 了解更多信息。

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-30
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多