[英]Select the same period every year in R
這看起來很簡單,但我找不到簡單的解決方案。 我正在研究 25 年(2024-2050 年)中每一天的未來流量預測。 我只對每年4 月 11 日至 6 月 10 日這 61 天期間的流量感興趣。 我想從每年這個時期內的 seq 和 Data 列中提取數據,並將其放在一個數據框中。
示例數據:
library(xts)
seq <- timeBasedSeq('2024-01-01/2050-12-31')
Data <- xts(1:length(seq),seq)
我想在 4 月 11 日至 6 月 10 日之間的所有日期以及所有年份(2024-2050 年)中實現類似的目標。 這是一個縮短的示例輸出:
seq_x <- c("2024-04-11","2024-06-10","2025-04-11","2025-06-10","2026-04-11","2027-06-10",
"2027-04-11", "2027-06-10")
Data_x <- c(102, 162, 467, 527, 832, 892, 1197, 1257)
output <- data.frame(seq_x, Data_x)
這個問題類似於: 計算每年特定時間段的平均值並在 r 中選擇多個年份的日期范圍,但沒有為我關於如何在多年中提取同一時期的問題提供有效的答案。
使用它創建一個 mmdd 字符串和子集:
mmdd <- format(time(Data), "%m%d")
Data1 <- Data[mmdd >= "0411" & mmdd <= "0610"]
這些也行。 他們將日期向后移動 10 天,在這種情況下它與四月和五月重合
Data2 <- Data[format(time(Data)-10, "%m") %in% c("04", "05")]
或者
Data3 <- Data[ cycle(as.yearmon(time(Data)-10)) %in% 4:5 ]
命令fortify.zoo(x)
可用於將 xts 對象x
轉換為數據框。
這是一個基本的R方法:
dates <- index(Data)
month <- as.integer(format(dates, '%m'))
day <- as.integer(format(dates, '%d'))
result <- Data[month == 4 & day >= 11 | month == 5 | month == 6 & day <= 10]
result
#2024-04-11 102
#2024-04-12 103
#2024-04-13 104
#2024-04-14 105
#2024-04-15 106
#2024-04-16 107
#...
#...
#2024-06-07 159
#2024-06-08 160
#2024-06-09 161
#2024-06-10 162
#2025-04-11 467
#2025-04-12 468
#...
#...
這是一個選項。 通過做一組year
的“seq_x”的,然后summarise
創建一個list
,基於該子集化“數據”列first
和last
“seq_x”的元素和select
列
library(dplyr)
library(lubridate)
library(tidyr)
library(purrr)
output %>%
group_by(year = year(seq_x)) %>%
summarise(new = list(Data[str_c(first(seq_x), last(seq_x), sep="::")]),
.groups = 'drop') %>%
pull(new) %>%
invoke(rbind, .)
# [,1]
#2024-04-11 102
#2024-04-12 103
#2024-04-13 104
#2024-04-14 105
#2024-04-15 106
#2024-04-16 107
# ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.