簡體   English   中英

計算每年特定時間段的平均值

[英]Calculating average for certain time period in every year

我需要每年為我的數據計算季節性平均值,平均值的計算不在同一日歷年中。 我已經按日期定義了季節,並希望計算每年該時間段的平均溫度,降水量等(例如12/21/198102/15/1982 / 12/21/1982 02/15/1983 02/15/1982 / 12/21/198202/15/1983 ),因此上。

在R中有有效的方法嗎?

以下是我的數據:

library(xts)
seq <- timeBasedSeq('1981-01-01/1985-06-30') 
Data <- xts(1:length(seq),seq) 

謝謝

這是一個使用tidyverse語法的以數據框為中心的方法(如果願意,可以將其翻譯為基數R):

library(tidyverse)

df_in <- tibble(
    date = seq(as.Date('1981-01-01'), as.Date('1985-06-30'), by = 'day'), 
    x = seq_along(date)
)

str(df_in)
#> Classes 'tbl_df', 'tbl' and 'data.frame':    1642 obs. of  2 variables:
#>  $ date: Date, format: "1981-01-01" "1981-01-02" ...
#>  $ x   : int  1 2 3 4 5 6 7 8 9 10 ...

df_out <- df_in %>% 
    # reformat data to keep months and days, but use identical year, so...
    mutate(same_year = as.Date(format(date, '1970-%m-%d'))) %>% 
    # ...we can subset to rows we care about with simpler logic
    filter(same_year < as.Date('1970-02-15') | same_year > as.Date('1970-12-21')) %>% 
    # shift so all in one year and use for grouping
    group_by(run = as.integer(format(date - 60, '%Y'))) %>% 
    summarise(    # aggregate each gruop
        start_date = min(date), 
        end_date = max(date), 
        mean_x = mean(x)
    )

df_out
#> # A tibble: 5 x 4
#>     run start_date end_date   mean_x
#>   <int> <date>     <date>      <dbl>
#> 1  1980 1981-01-01 1981-02-14     23
#> 2  1981 1981-12-22 1982-02-14    383
#> 3  1982 1982-12-22 1983-02-14    748
#> 4  1983 1983-12-22 1984-02-14   1113
#> 5  1984 1984-12-22 1985-02-14   1479

如果我們將時間提前11天,那么我們想要的日期是2月26日或之前的日期,因此,讓tt是這樣的日期向量,而ok是一個邏輯向量,如果相應的tt元素在2月26日或之前是TRUE。 最后在期末之前匯總Data[ok]

tt <- time(Data) + 11
ok <- format(tt, "%m-%d") < "02-26"
aggregate(Data[ok], as.integer(as.yearmon(tt))[ok], mean)

贈送:

1981   23.0
1982  382.5
1983  747.5
1984 1112.5
1985 1478.5

如果您想在沒有xts的情況下進行操作,那么假設我們的輸入是DF嘗試以下操作:

DF <- fortify.zoo(Data) # input

tt <- DF[, 1] + 11
ok <- format(tt, "%m-%d") < "02-26"
year <- as.numeric(format(tt, "%Y"))
aggregate(DF[ok, -1, drop = FALSE], list(year = year[ok]), mean)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM