1

3 年間のデータがある場合:

データ = (x1:x1096)

この方法で平均を計算したい:

     [x1+x366(the first day in the second year)+ x731(the first day in the third year)]/3
     [x2+x367(the second day in the second year)+ x732(the second day in the third year)]/3

365 日まで続く:

     [x365+x730(the last day in the second year)+ x1096(the last day in the third year)]/3

最後に私はそこ365 valuesから抜け出します。

     dat= c(1:1096) 

これを行う方法について何か考えはありますか?

4

3 に答える 3

3

data.tableここでは非常に便利です: (基本R的なソリューションは完全に実行可能ですが!):

> set.seed(1)
> dat <- data.table(date=seq(as.Date("2010-01-01"), as.Date("2012-12-31"), "days"),
+                   var=rnorm(1096))
> dat
            date          var
   1: 2010-01-01 -0.626453811
   2: 2010-01-02  0.183643324
   3: 2010-01-03 -0.835628612
   4: 2010-01-04  1.595280802
   5: 2010-01-05  0.329507772
  ---                        
1092: 2012-12-27  0.711213964
1093: 2012-12-28 -0.337691156
1094: 2012-12-29 -0.009148952
1095: 2012-12-30 -0.125309208
1096: 2012-12-31 -2.090846097

> dat[, mean(var), by=list(month=month(date), mday(date))]
     month mday          V1
  1:     1    1 -0.16755484
  2:     1    2  0.59942582
  3:     1    3 -0.44336168
  4:     1    4  0.01297244
  5:     1    5 -0.20317854
 ---                       
362:    12   28 -0.18076284
363:    12   29  0.07302903
364:    12   30 -0.01790655
365:    12   31 -0.87164859
366:     2   29 -0.78859794

2 月 29 日が最後です。これ[.data.tableは、その日のグループが ( と の) 最後に一意の組み合わせ (month(date)mday(date)) が見つかったときであり、2012 年に初めて表示されるためです。結果が得られたら、キーを割り当てて、テーブルを並べ替えることができます。

> result <- dat[, mean(var), by=list(month=month(date), mday(date))]
> setkey(result, month, mday)
> result
     month mday          V1
  1:     1    1 -0.16755484
  2:     1    2  0.59942582
  3:     1    3 -0.44336168
  4:     1    4  0.01297244
  5:     1    5 -0.20317854
 ---                       
362:    12   27 -0.60348463
363:    12   28 -0.18076284
364:    12   29  0.07302903
365:    12   30 -0.01790655
366:    12   31 -0.87164859
于 2013-10-09T11:44:10.930 に答える
2

もしかして、こんな感じ?ベクトルよりもわずかに小さい例で試してみました1:1096-代わりに、1年に5つの値を使用しました。

# the data, here 3 years with 5 values per year. 
dat <- 1:15

# put your vector in a matrix
# by default, the matrix is filled column-wise
# thus, each column corresponds to a year, and each row to day of year
mm <- matrix(dat, ncol = 3)

# calculate row means
mm <- cbind(mm, rowMeans(mm))
mm
#      [,1] [,2] [,3] [,4]
# [1,]    1    6   11    6
# [2,]    2    7   12    7
# [3,]    3    8   13    8
# [4,]    4    9   14    9
# [5,]    5   10   15   10

@Micheleの回答と同じ(つまり)「完全な」データbaseを使用して、うるう年を説明する 別の代替案を更新します。set.seed(1)

df2 <- aggregate(var ~ format(date, "%m-%d"), data = dat, FUN = mean)
head(df2)

#   format(date, "%m-%d")         var
# 1                 01-01 -0.16755484
# 2                 01-02  0.59942582
# 3                 01-03 -0.44336168
# 4                 01-04  0.01297244
# 5                 01-05 -0.20317854
# 6                 01-06 -0.55350137
于 2013-10-09T10:33:31.260 に答える