【问题标题】:Moving average over 5 years with irregular dates5 年以上移动平均,日期不规则
【发布时间】:2017-03-19 09:16:17
【问题描述】:

我有大量文件(约 1200 个),每个文件都包含大量时间序列,其中包含有关地下水高度的数据。系列的开始日期和长度因每个文件而异。日期之间可能存在较大的数据间隔,例如(此类文件的一小部分):

Date        Height (cm)
14-1-1980   7659
28-1-1980   7632
14-2-1980   7661
14-3-1980   7638
28-3-1980   7642
14-4-1980   7652
25-4-1980   7646
14-5-1980   7635
29-5-1980   7622
13-6-1980   7606
27-6-1980   7598
14-7-1980   7654
28-7-1980   7654
14-8-1980   7627
28-8-1980   7600
12-9-1980   7617
14-10-1980  7596
28-10-1980  7601
14-11-1980  7592
28-11-1980  7614
11-12-1980  7650
29-12-1980  7670
14-1-1981   7698
28-1-1981   7700
13-2-1981   7694
17-3-1981   7740
30-3-1981   7683
14-4-1981   7692
14-5-1981   7682
15-6-1981   7696
17-7-1981   7706
28-7-1981   7699
28-8-1981   7686
30-9-1981   7678
17-11-1981  7723
11-12-1981  7803
18-2-1982   7757
16-3-1982   7773
13-5-1982   7753
11-6-1982   7740
14-7-1982   7731
15-8-1982   7739
14-9-1982   7722
14-10-1982  7794
15-11-1982  7764
14-12-1982  7790
14-1-1983   7810
28-3-1983   7836
28-4-1983   7815
31-5-1983   7857
29-6-1983   7801
28-7-1983   7774
24-8-1983   7758
28-9-1983   7748
26-10-1983  7727
29-11-1983  7782
27-1-1984   7801
28-3-1984   7764
27-4-1984   7752
28-5-1984   7795
27-7-1984   7748
27-8-1984   7729
28-9-1984   7752
26-10-1984  7789
28-11-1984  7797
18-12-1984  7781
28-1-1985   7833
21-2-1985   7778
22-4-1985   7794
28-5-1985   7768
28-6-1985   7836
26-8-1985   7765
19-9-1985   7760
31-10-1985  7756
26-11-1985  7760
20-12-1985  7781
17-1-1986   7813
28-1-1986   7852
26-2-1986   7797
25-3-1986   7838
22-4-1986   7807
27-5-1986   7785
24-6-1986   7787
26-8-1986   7744
23-9-1986   7742
22-10-1986  7752
1-12-1986   7749
17-12-1986  7758

我想计算 5 年的平均身高。因此,在示例 14-1-1980 + 5 年、14-1-1985 + 5 年的情况下,...。每次计算平均值时,数据点的数量都不同。 5 年后的日期很可能不会作为数据点出现在数据集中。因此,我认为我需要以某种方式告诉 R 在某个时间跨度内取平均值。

我在互联网上进行了搜索,但没有找到适合我需要的东西。许多有用的包,如 uts、zoo、lubridate 和传递的函数聚合。我没有更接近解决方案,而是越来越困惑哪种方法最适合我的问题。

提前非常感谢!

【问题讨论】:

  • 首先您可以阅读所有内容并将 rbind 合并到一个数据帧中。
  • 也许可以看看zoo 包中的rollapply

标签: r date time-series


【解决方案1】:

正如@vagabond 指出的那样,您需要将 1200 个文件合并到一个数据框中(plyr 包可以让您执行一些简单的操作,例如:data.all <- adply(dir([DATA FOLDER]), 1, read.csv)

获得数据后,第一步是将Date 列转换为正确的 POSIXct 日期数据。现在数据似乎是字符串,我们希望它们具有底层的数字表示(POSIXct 可以):

library(lubridate)
df$date.new <- as.Date(dmy(df$Date))

       Date Height   date.new
1 14-1-1980   7659 1980-01-14
2 28-1-1980   7632 1980-01-28
3 14-2-1980   7661 1980-02-14
4 14-3-1980   7638 1980-03-14
5 28-3-1980   7642 1980-03-28
6 14-4-1980   7652 1980-04-14

请注意,date.new 列看起来像一个字符串,但实际上是日期数据,可以通过数字运算(加法、比较等)进行处理。

接下来,我们可能会构建一组日期周期,并在其中计算平均值。您的示例提到了 5 年,但根据您提供的数据,这不是一个非常具有说明性的示例。所以在这里我创建了从 1980 年 1 月 14 日到 1985 年 1 月 14 日之间的每一天开始的 1 年期

date.start <- as.Date(as.Date('1980-01-14') : as.Date('1985-01-14'), origin = '1970-01-01')
date.end <- date.start + years(1)
dates <- data.frame(start = date.start, end = date.end)

       start        end
1 1980-01-14 1981-01-14
2 1980-01-15 1981-01-15
3 1980-01-16 1981-01-16
4 1980-01-17 1981-01-17
5 1980-01-18 1981-01-18
6 1980-01-19 1981-01-19

然后我们可以使用 dplyr 包遍历这个数据框的每一行并计算出Height 的汇总平均值:

library(dplyr)
df.mean <- dates %>% 
    group_by(start, end) %>% 
    summarize(height.mean = mean(df$Height[df$date.new >= start & df$date.new < end]))

       start        end height.mean
      <date>     <date>       <dbl>
1 1980-01-14 1981-01-14    7630.273
2 1980-01-15 1981-01-15    7632.045
3 1980-01-16 1981-01-16    7632.045
4 1980-01-17 1981-01-17    7632.045
5 1980-01-18 1981-01-18    7632.045
6 1980-01-19 1981-01-19    7632.045

【讨论】:

  • 正如我所解释的那样,@BartM 正在寻找某个日期和该日期前 5 年之间的数据点的平均值。您还为每个缺失的日期创建了新期间。这不是 BartM 要求恕我直言的。
  • 这个问题在这一点上有点模棱两可,但如果您想要仅基于现有数据中存在的日期的期间,dates.start &lt;- df$date.new 应该这样做。
【解决方案2】:

foverlaps 函数是恕我直言,适合这种情况:

library(data.table)
library(lubridate)

# convert to a data.table with setDT()
# convert the 'Date'-column to date-format
# create a begin & end date for the required period
setDT(dat)[, Date := as.Date(Date, '%d-%m-%Y')                      
           ][, `:=` (begindate = Date, enddate = Date + years(1))]

# set the keys (necessary for the foverlaps function)
setkey(dat, begindate, enddate)

res <- foverlaps(dat, dat, by.x = c(1,3))[, .(moving.average = mean(i.Height)), Date]

结果:

> head(res,15)
          Date moving.average
 1: 1980-01-14       7633.217
 2: 1980-01-28       7635.000
 3: 1980-02-14       7637.696
 4: 1980-03-14       7636.636
 5: 1980-03-28       7641.273
 6: 1980-04-14       7645.261
 7: 1980-04-25       7644.955
 8: 1980-05-14       7646.591
 9: 1980-05-29       7647.143
10: 1980-06-13       7648.400
11: 1980-06-27       7652.900
12: 1980-07-14       7655.789
13: 1980-07-28       7660.550
14: 1980-08-14       7660.895
15: 1980-08-28       7664.000

现在,对于每个日期,您可以获得该日期和该日期前一年的所有值的平均值。

【讨论】:

    【解决方案3】:

    嘿,我刚看到你的问题就试过了!!!在样本数据帧上运行。看懂代码后自己试一下,然后告诉我!

    Bdw 不是以 5 年为间隔,而是仅使用 2 个月(2*30 = 大约 2 个月)作为间隔!

    df = data.frame(Date = c("14-1-1980", "28-1-1980", "14-2-1980", "14-3-1980", "28-3-1980",
                         "14-4-1980", "25-4-1980", "14-5-1980", "29-5-1980", "13-6-1980:",
                         "27-6-1980", "14-7-1980", "28-7-1980", "14-8-1980"), height = 1:14)
    
    # as.Date(df$Date, "%d-%m-%Y")
    
    df1 = data.frame(orig = NULL, dest = NULL, avg_ht = NULL)
    orig = as.Date(df$Date, "%d-%m-%Y")[1]
    dest = as.Date(df$Date, "%d-%m-%Y")[1] + 2*30 #approx 2 months
    dest_final = as.Date(df$Date, "%d-%m-%Y")[14]
    
    while (dest < dest_final){
      m = mean(df$height[which(as.Date(df$Date, "%d-%m-%Y")>=orig &
                               as.Date(df$Date, "%d-%m-%Y")<dest )])
      df1 = rbind(df1,data.frame(orig=orig,dest=dest,avg_ht=m))
      orig = dest
      dest = dest + 2*30
      print(paste("orig:",orig, " + ","dest:",dest))
    }
    
    > df1
            orig       dest avg_ht
    1 1980-01-14 1980-03-14    2.0
    2 1980-03-14 1980-05-13    5.5
    3 1980-05-13 1980-07-12    9.5
    

    我希望这也适用于你

    【讨论】:

    • 因为我使用的是 while() 循环,所以代码会很慢。但我希望这能让你真正开始你的探索!!更新我的结果!
    • 您的示例运行良好,当我在所有文件上运行它时,我会看看效果如何。非常感谢。
    • @BartM 解决方案如何解决您的问题。请接受其中一个答案。关注stackoverflow.com/help/someone-answers
    【解决方案4】:

    这是我最好的尝试,但请记住,我使用的是年份而不是完整日期,即根据您提供的示例,我是 1980 年初至 1984 年底的平均值。

    dat<-read.csv("paixnidi.csv")
    install.packages("stringr")
    library(stringr)
    dates<-dat[,1]
    #extract the year of each measurement
    years<-as.integer(str_sub(dat[,1], start= -4))
    spread_y<-years[length(years)]-years[1]
    
    ind<-list()
    #find how many 5-year intervals there are
    groups<-ceiling(spread_y/4)
    meangroups<-matrix(0,ncol=2,nrow=groups)
    k<-0
    for (i in 1:groups){
      #extract the indices of the dates vector whithin the 5-year period
      ind[[i]]<-which(years>=(years[1]+k)&years<=(years[1]+k+4),arr.ind=TRUE)
      meangroups[i,2]<-mean(dat[ind[[i]],2])
      meangroups[i,1]<-(years[1]+k)
      k<-k+5
    }
    
    colnames(meangroups)<-c("Year:Year+4","Mean Height (cm)")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-17
      • 2013-07-13
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多