我有一個資料框,代表兩條河流的兩年每日溫度時間序列。我已經確定溫度何時高于或低于峰值溫度。當溫度高于或低于 10 度的閾值溫度時,我還創建了一個運行長度 ID 列。
如何獲得每個站點和年份的第一天以及以下條件:
- 最大運行長度 & 低于峰值 =
TRUE - 最大運行長度和峰值以上 =
TRUE
示例資料:
library(ggplot2)
library(lubridate)
library(dplyr)
library(dataRetrieval)
siteNumber <- c("01432805","01388000") # United States Geological Survey site numbers
parameterCd <- "00010" # temperature
statCd <- "00003" # mean
startDate <- "1996-01-01"
endDate <- "1997-12-31"
dat <- readNWISdv(siteNumber, parameterCd, startDate, endDate, statCd=statCd) # obtains the timeseries from the USGS
dat <- dat[,c(2:4)]
colnames(dat)[3] <- "temperature"
# To view at the time series
ggplot(data = dat, aes(x = Date, y = temperature))
geom_point()
theme_bw()
facet_wrap(~site_no)
創建上述列
dat <- dat %>%
mutate(year = year(Date),
doy = yday(Date)) %>% # doy = day of year
group_by(site_no, year) %>%
mutate(lt_10 = temperature <= 10,
peak_doy = doy[which.max(temperature)],
below_peak = doy < peak_doy,
after_peak = doy > peak_doy,
run = data.table::rleid(lt_10))
View(dat)
理想的輸出如下所示:
site_no year doy_below doy_after
1 01388000 1996 111 317
2 01388000 1997 112 312
3 01432805 1996 137 315
4 01432805 1997 130 294
doy_afterafter_peak == TRUE= & max(run)when的第一行group_by(site_no,year)
doy_belowbelow_peak == TRUE= & max(run)when的第一行group_by(site_no,year)
- 對于
site_no= 01388000 inyear= 1996,max(run)whenbelow_peak == TRUE是 4。第一行 whenrun= 4 并且below_peak == TRUE對應于1996-04-20adoy= 111 的日期。
uj5u.com熱心網友回復:
由于資料已經分組,只需summarise提取 'doy' 其中'below_peak' 或 'after_peak' 中值為 TRUE 的子集,并獲取run' maxdoy ' 的元素runfirst
library(dplyr)
dat %>%
summarise(doy_below = first(doy[run == max(run[below_peak])]),
doy_above = first(doy[run == max(run[after_peak])]), .groups = 'drop')
-輸出
# A tibble: 4 × 4
site_no year doy_below doy_above
<chr> <dbl> <dbl> <dbl>
1 01388000 1996 111 317
2 01388000 1997 112 312
3 01432805 1996 137 315
4 01432805 1997 130 294
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/522756.html
標籤:rdplyr
上一篇:如何在ggplot中修復我的x和y軸,所有日期和id編號都正確反映?
下一篇:通過不同的公共列組合遷移進出資料
