【问题标题】:Apportion number of days per month between two dates in R code?在R代码中的两个日期之间每月分配天数?
【发布时间】:2019-12-02 09:06:20
【问题描述】:

我对 R 编程非常陌生,正在尝试确定两个日期之间每月分配的天数。

我有一个具有以下结构的数据集: 从日期 迄今为止 数量

示例数据:

2019-06-15 2019-09-10 55
2019-07-11 2019-10-05 17

我想调用一个返回数据集/向量的函数?它包含 3 个值,因为 from_date 和 to_date 之间的最大差异为 3 个月。

我尝试使用lubridate::floor_date()to_date 向后工作

【问题讨论】:

  • 你想要的输出是什么?不清楚call a function that returns a dataset/vector? that holds 3 values as there will be a maximum difference between from_date and to_date of 3 months.
  • 我不确定这是否是您期望的结果,但我认为这是寻找解决方案的良好开端。 df <- data.frame("from_date" = c("2019-06-15", "2019-09-10"), "to_date" = c("2019-07-11", "2019-10-05"), stringsAsFactors = FALSE)df$quantity <- as.Date(as.character(df$to_date), format="%Y-%m-%d") - as.Date(as.character(df$from_date), format="%Y-%m-%d")这个代码可以让你知道两个日期之间的天数

标签: r


【解决方案1】:

不确定您是否正在寻找如下结果:

df$quantity <-  with(df,as.Date(to_date)-as.Date(from_date))

df$quantity <- apply(df, 1, function(v) diff(as.Date(v)))

屈服

> df
   from_date    to_date quantity
1 2019-06-15 2019-09-10       87
2 2019-07-11 2019-10-05       86

数据

df <- structure(list(from_date = structure(1:2, .Label = c("2019-06-15", 
"2019-07-11"), class = "factor"), to_date = structure(1:2, .Label = c("2019-09-10", 
"2019-10-05"), class = "factor")), class = "data.frame", row.names = c(NA, 
-2L))

【讨论】:

  • 如果那是 OP 真正想要的,那么这里就不需要applyas.Date(df$to_date) - as.Date(df$from_date)
  • 首先,感谢那些发表评论的人,非常感谢您抽出宝贵的时间。我希望得到一个包含每个月天数的结果,第 1 行:15、31、31、10。这代表 6 月从 from_date 到 eom 开始的 6 月天数,然后是整个 7 月、整个 8 月和最后几天直到 to_date。就是从每个月的天数中分摊87天
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多