【发布时间】:2018-03-28 21:13:38
【问题描述】:
我有 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
我想要的是在df.ref 中的行,使用df.ref 中的index 值和
将df 中 index1 到 index2、index1 到 index3 和 index1 到 index4 之间的降雨量相加。例如:
使用df.ref,对于loc.id = 1 和year == 2001,将df 中的降雨量相加,从250 到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 非常大。谁能告诉我如何使这个更快。
【问题讨论】:
-
同一id和年份有多个记录
subset(df.ref, loc.id == 1 & years == 2001)应该是这样吗? -
"将
df的降雨量从 250 到 264、250 到 280、250 到 296 求和" 你的意思是把df的降雨量从 求和行 250 到 264、250 到 280 等等? -
使用
data.table搜索非等连接 -
@PoGibas 抱歉,数据中有错误。我已经修好了。它应该只有一个 id 和 year 的记录
-
@MauritsEvers 是的,我就是这个意思。
标签: r dplyr data.table tidyverse non-equi-join