[英]how to calculate the mean of a variable between two date
我想計算兩個日期之間的變量平均值,以下是可重現的數據框。
year <- c(1996,1996,1996,1996,1996,1996,1996,1996,1996,1996,1996,1996,
1996,1996,1996,1996,1996,1996,1996,1996,1996,1996,1996,1996,
1997,1997,1997,1997,1997,1997,1997,1997,1997,1997,1997,1997,
1997,1997,1997,1997,1997,1997,1997,1997,1997,1997,1997,1997)
month <- c("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")
station <- c("A","A","A","A","A","A","A","A","A","A","A","A",
"B","B","B","B","B","B","B","B","B","B","B","B")
concentration <- as.numeric(round(runif(48,20,40),1))
df <- data.frame(year,month,station,concentration)
id <- c(1,2,3,4)
station1996 <- c("A","A","B","B")
station1997 <- c("B","A","A","B")
start <- c("06/01/1996","07/01/1996","07/01/1996","08/01/1996")
end <- c("04/01/1997","04/01/1997","04/01/1997","05/01/1997")
participant <- data.frame(id,station1996,station1997,start,end)
participant$start <- as.Date(participant$start, format = "%m/%d/%Y")
participant$end <- as.Date(participant$end, format = "%m/%d/%Y")
所以我有兩個數據集如下
df
year month station concentration
1 1996 JAN A 24.4
2 1996 FEB A 37.0
3 1996 MAR A 39.5
4 1996 APR A 28.0
...
45 1997 SEP B 37.7
46 1997 OCT B 35.2
47 1997 NOV B 26.8
48 1997 DEC B 40.0
participant
id station1996 station1997 start end
1 1 A B 1996-06-01 1997-04-01
2 2 A A 1996-07-01 1997-04-01
3 3 B A 1996-07-01 1997-04-01
4 4 B B 1996-08-01 1997-05-01
對於每個ID,我想計算開始日期和結束日期(月份)之間的平均濃度。 注意,該站可能會在幾年之間變化。
例如,對於id = 1,我想計算1996年6月到1997年4月之間的平均濃度。這應該基於A站從1996年6月到1996年12月以及B站從1997年1月到1997年4月的濃度。
有人可以幫忙嗎?
非常感謝你。
這是一個data.table解決方案。 基本思想是將每個id
的開始-結束范圍內的所有日期枚舉為yearmon
,然后將其用作濃度表df
的索引。 這有點令人費解,所以希望有人會來給您展示一種更簡單的方法。
library(data.table)
library(zoo) # for as.yearmon(...)
setDT(df) # convert to data.table
setDT(participant)
df[, yrmon:= as.yearmon(paste(year,month,sep="-"), format="%Y-%B")] # add year-month column
p.melt <- reshape(participant, varying=2:3, direction="long", sep="", timevar="year")
x <- participant[, .(date=seq(start,end,by="month")), by=id]
x[, c("year","yrmon"):=.(year(date),as.yearmon(date))] # add year and year-month
x[p.melt, station:=station, on=c("id","year")] # add station
x[df, conc:= concentration, on=c("yrmon","station"), nomatch=0] # add concentration
setorder(x,id) # not necessary, but makes it easier to interpret x
result <- x[, .(mean.conc=mean(conc)), by=id] # mean(conc) by id
result
# id mean.conc
# 1: 1 28.61818
# 2: 2 28.56000
# 3: 3 28.44000
# 4: 4 29.60000
因此,首先我們將所有內容都轉換為data.tables。 然后,我們將yrmon
列添加到df
以便以后進行索引。 然后,我們通過將participant
重塑為長格式來創建p.melt
,以便站點位於一列中,而指標(1996或1997)位於單獨的列中。 然后,我們創建一個臨時表x
,其中每個id
帶有日期序列,並為每個日期添加year和yrmon。 然后,將其與id
和year
p.melt
合並,以將樁號列添加到x
。 然后,使用yrmon
和station
將x
與df
合並以獲得適當的濃度。 然后我們簡單地使用mean(...)
在x
通過id
聚合conc
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.