r - 分组 ID 列表上的分配函数
问题描述
我有一个带有 ID、开始日期、结束日期以及收入和成本值的数据框。
table <- data.frame(id = c(1, 2, 3),
start = c("2018-01-01", "2018-02-05", "2018-05-30"),
end = c("2018-01-31", "2018-03-26", "2018-08-31"),
income = c(100, 225, 399),
costs = c(37, 98, 113))
table$start <- as.Date(table$start)
table$end <- as.Date(table$end)
结果是:
id start end income costs
1 2018-01-01 2018-01-31 100 37
2 2018-02-05 2018-03-26 225 98
3 2018-05-30 2018-08-31 399 113
就像这个问题一样,其中一些时间段跨越 n 个月,我想按月汇总收入和成本。对于那些与跨越两个月、三个月或更长时间的时期有关的金额,我想在两个月、三个月或 n 个月之间线性分配它们。
问题是我还想保留 id,并对两个变量执行操作(不是像之前提出的问题那样),这使整个事情变得复杂。
我期望得到的是下表:
id date income costs
1 2018-01 100 37
2 2018-02 108 47.04
2 2018-03 117 50.96
3 2018-05 8.489362 2.404255
3 2018-06 127.340426 36.063830
3 2018-07 131.585106 37.265957
3 2018-08 131.585106 37.265957
我尝试在由 id 创建的数据框列表上使用 rbindlist,并使用以下函数:
explode <- function(start, end, income) {
dates <- seq(start, end, "day")
n <- length(dates)
rowsum(rep(income, n) / n, format(dates, "%Y-%m"))
}
Map(explode, table$start, table$end, table$income)
但当然它只返回内部的行和值和未命名的列表。
任何帮助将不胜感激。谢谢!
解决方案
您的解决方案可能会奏效。简单地,添加一个新参数Map
并扩展您的函数cbind
以结合收入和成本,然后rbind
生成列表Map
:
explode <- function(start, end, income, costs) {
dates <- seq(start, end, "day")
n <- length(dates)
cbind.data.frame(
date = format(start, "%Y-%m"),
income = rowsum(rep(income, n) / n, format(dates, "%Y-%m")),
costs = rowsum(rep(costs, n) / n, format(dates, "%Y-%m"))
)
}
data_list <- Map(explode, table$start, table$end, table$income, table$costs)
final_df <- do.call(rbind, data_list)
final_df
# date income costs
# 2018-01 100.000000 37.000000
# 2018-02 108.000000 47.040000
# 2018-03 117.000000 50.960000
# 2018-05 8.489362 2.404255
# 2018-06 127.340426 36.063830
# 2018-07 131.585106 37.265957
# 2018-08 131.585106 37.265957
推荐阅读
- html - Stack objects as a multiple item selector with html and css
- javascript - How to identify an Asynchronous function in Javascript?
- r - Getting as the last table header
- javascript - 为什么在 clearTimeout 之后 SetTimeout 代码仍然执行
- javascript - 逗号和括号之间的 0 用于什么?
- javascript - Javascript Solr(方面)查询脚本无法正常工作
- sql - How to output information in Oracle db using in other pl/sql block?
- java - 还有其他获取日期格式的输入的方法吗?
- python - 如何安装 HDBSCAN 模块、python 3.7、windows 10
- ios - 在不影响发布者类型的情况下向发布者转换链添加额外的逻辑