![](/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.