我有两个数据帧,一个按日包含数据,另一个包含不规则时间多天间隔的数据。例如:
一种具有不规则时间间隔降水数据的数据帧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_daily中start_date和end_date之间的日期范围来总结数据帧precip_range中的start_date列(计数和precip和)。有什么最好的办法吗?
发布于 2014-06-30 18:37:42
您可以使用start_dates从precip_range作为休息到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以获得每个范围的总数(标有开始日期的范围)
发布于 2014-06-30 19:41:01
或
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 3https://stackoverflow.com/questions/24496421
复制相似问题