我有 10 年内 10 个地点的每日降雨量数据
set.seed(123)
df <- data.frame(loc.id = rep(1:10, each = 10*365),years = rep(rep(2001:2010,each = 365),times = 10),
day = rep(rep(1:365,times = 10),times = 10), rain = runif(min = 0 , max = 35, 10*10*365))
我有一个单独的数据框,它有特定的日子,我想用它来总结降雨量df
df.ref <- data.frame(loc.id = rep(1:10, each = 10),
years = rep(2001:2010,times = 10),
index1 = rep(250,times = 10*10),
index2 = sample(260:270, size = 10*10,replace = T),
index3 = sample(280:290, size = 10*10,replace = T),
index4 = sample(291:300, size= 10*10,replace = T))
df.ref
loc.id years index1 index2 index3 index4
1: 1 2001 250 264 280 296
2: 1 2002 250 269 284 298
3: 1 2003 250 268 289 293
4: 1 2004 250 266 281 295
5: 1 2005 250 260 289 293
我想要的是 in 中的行df.ref,使用 in 中的index值df.ref并将dfindex1 到 index2、index1 到 index3 和 index1 到 index4 之间的降雨量相加。例如:
使用df.ref,对于 loc.id = 1 和 year == 2001,将df250 到 264、250 到 280、250 到 296 的降雨量相加(如图所示df.ref) 同样,对于 2002 年,对于 loc.id = 1,求和降雨量从 250 到 269、250 到 284、250 到 298。
我这样做了:
library(dplyr)
ptm <- proc.time()
dat <- df.ref %>% left_join(df)
index1.cal <- dat %>% group_by(loc.id,years) %>% filter(day >= index1 & day <= index2) %>% summarise(sum.rain1 = sum(rain))
index2.cal <- dat %>% group_by(loc.id,years) %>% filter(day >= index1 & day <= index3) %>% summarise(sum.rain2 = sum(rain))
index3.cal <- dat %>% group_by(loc.id,years) %>% filter(day >= index1 & day <= index4) %>% summarise(sum.rain3 = sum(rain))
all.index <- index1.cal %>% left_join(index2.cal) %>% left_join(index3.cal))
proc.time() - ptm
user system elapsed
2.36 0.64 3.06
我希望使我的代码更快,因为我的实际代码df.ref很大。谁能告诉我如何让这个更快。