![](/img/trans.png)
[英]Group data in data frame based on date range in second data frame In R
[英]Summarize R data frame based on a date range in a second data frame
我有两个数据框,一个包括按天的数据,另一个包含不规则时间多日间隔的数据。 例如:
一个数据框, precip_range
包含不规则时间间隔的降水数据:
start_date<-as.Date(c("2010-11-01", "2010-11-04", "2010-11-10"))
end_date<-as.Date(c("2010-11-03", "2010-11-09", "2010-11-12"))
precipitation<-(c(12, 8, 14))
precip_range<-data.frame(start_date, end_date, precipitation)
和数据帧precip_daily
与逐日降水资料:
day<-as.Date(c("2010-11-01", "2010-11-02", "2010-11-03", "2010-11-04", "2010-11-05",
"2010-11-06", "2010-11-07", "2010-11-08", "2010-11-09", "2010-11-10",
"2010-11-11", "2010-11-12"))
precip<-(c(3, 1, 2, 1, 0.25, 1, 3, 0.33, 0.75, 0.5, 1, 2))
precip_daily<-data.frame(day, precip)
在此示例中, precip_daily
表示由模型估计的每日降水量,而precip_range
表示特定日期范围的测量累积降水量。 我试图将建模与测量数据进行比较,这需要同步时间段。
所以,我想总结的precip
在数据帧列precip_daily
(观察和总和计数precip
通过的日期日期范围) start_date
和end_date
在数据帧precip_range
。 有关最佳方法的任何想法吗?
您可以使用precip_range
的start_dates作为break( cut()
来对每日值进行分组。 例如
rng <- cut(precip_daily$day,
breaks=c(precip_range$start_date, max(precip_range$end_date)),
include.lowest=T)
在这里,我们使用data.frame范围内的开始日期来每日剪切值。 我们肯定会包含最低值并停在最大的最终值。 如果我们将其与我们看到的每日价值合并
cbind(precip_daily, rng)
# day precip rng
# 1 2010-11-01 3.00 2010-11-01
# 2 2010-11-02 1.00 2010-11-01
# 3 2010-11-03 2.00 2010-11-01
# 4 2010-11-04 1.00 2010-11-04
# 5 2010-11-05 0.25 2010-11-04
# 6 2010-11-06 1.00 2010-11-04
# 7 2010-11-07 3.00 2010-11-04
# 8 2010-11-08 0.33 2010-11-04
# 9 2010-11-09 0.75 2010-11-04
# 10 2010-11-10 0.50 2010-11-10
# 11 2010-11-11 1.00 2010-11-10
# 12 2010-11-12 2.00 2010-11-10
这表明这些值已经分组。 然后我们就可以做到
aggregate(cbind(count=1, sum=precip_daily$precip)~rng, FUN=sum)
# rng count sum
# 1 2010-11-01 3 6.00
# 2 2010-11-04 6 6.33
# 3 2010-11-10 3 3.50
获取每个范围的总数(标记为开始日期的范围)
要么
library(zoo)
library(data.table)
temp <- merge(precip_daily, precip_range, by.x = "day", by.y = "start_date", all.x = T)
temp$end_date <- na.locf(temp$end_date)
setDT(temp)[, list(Sum = sum(precip), Count = .N), by = end_date]
## end_date Sum Count
## 1: 2010-11-03 6.00 3
## 2: 2010-11-09 6.33 6
## 3: 2010-11-12 3.50 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.