【问题标题】:Assigning total to correct month from date range从日期范围将总计分配给正确的月份
【发布时间】:2019-03-19 15:33:41
【问题描述】:

我有一个包含以下格式的预订数据的数据集:

property   <- c('casa1', 'casa2', 'casa3')
check_in   <- as.Date(c('2018-01-01', '2018-01-30','2018-02-28'))
check_out  <- as.Date(c('2018-01-02', '2018-02-03', '2018-03-02'))
total_paid <- c(100,110,120)

df <- data.frame(property,check_in,check_out, total_paid)

我的目标是将每月的 total_paid 金额除以天数,并出于预算原因正确分配给每个月。
虽然casa1 没有问题,但casa2casa3 在两个月都保留了天数,并且由于这个问题,总数出现了偏差。

非常感谢任何帮助!

【问题讨论】:

  • 给定示例的预期输出是什么?
  • 嘿 Ronak,输出应该是这样的:一月

标签: r database accounting


【解决方案1】:

给你:

library(dplyr)
library(tidyr)
df %>% 
  mutate(id = seq_along(property), # make few variable to help
         day_paid = total_paid / as.numeric(check_out - check_in),
         date = check_in) %>% 
  group_by(id) %>% 
  complete(date = seq.Date(check_in, (check_out - 1), by = "day")) %>% # get date for each day of stay (except last)
  ungroup() %>% # make one row per day of stay
  mutate(month = cut(date, breaks = "month")) %>% # determine month of date
  fill(property, check_in, check_out, total_paid, day_paid) %>% 
  group_by(id, month) %>% 
  summarise(property = unique(property),
            check_in = unique(check_in),
            check_out = unique(check_out),
            total_paid = unique(total_paid),
            paid_month = sum(day_paid)) # summarise per month

结果:

# A tibble: 5 x 7
# Groups:   id [3]
     id month      property check_in   check_out  total_paid paid_month
  <int> <fct>      <fct>    <date>     <date>          <dbl>      <dbl>
1     1 2018-01-01 casa1    2018-01-01 2018-01-02        100        100
2     2 2018-01-01 casa2    2018-01-30 2018-02-03        110         55
3     2 2018-02-01 casa2    2018-01-30 2018-02-03        110         55
4     3 2018-02-01 casa3    2018-02-28 2018-03-02        120         60
5     3 2018-03-01 casa3    2018-02-28 2018-03-02        120         60

我希望它有点可读,但请询问是否有什么我应该解释的。惯例是人们不支付最后一天的住宿费用,所以我考虑到了这一点。

【讨论】:

  • 非常感谢,这正是我所需要的,而且非常简洁易读。也注意到我没有指定的内容(最后一天的住宿不支付)!
猜你喜欢
  • 2014-02-28
  • 1970-01-01
  • 2021-04-10
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多