2017-02-06 7 views
1

私は時系列解析には新しくxts(と一般にR)を使用していますので、質問の基本的な性質を許してください。xtsオブジェクトのデータを時間と第2の変数(因子)で集計する

私は、データを時間枠(例:月)と第2因子変数で集計したいと考えています。

  colour value 
2015-01-30 "Blue" "2" 
2015-03-15 "Blue" "9" 
2015-03-22 "Blue" "9" 
2015-08-13 "Blue" "5" 
2015-09-01 "Blue" "8" 
2015-11-10 "Red" "7" 
2016-04-26 "Blue" "2" 
2016-07-06 "Red" "9" 
2016-07-07 "Red" "6" 
2016-07-08 "Red" "2" 
2016-10-01 "Red" "6" 
2016-11-07 "Red" "2" 

は、私が使用して「値」変数をまとめることができます:

apply.monthly(df$value, FUN = mean) 

require(xts) 

# Create example df and convert it to an xts object 

date <- sample(seq(as.Date("2015/01/01"), as.Date("2016/12/31"), by="day"),12) 
colour <- c("Red", "Red", "Blue", "Blue", "Blue", "Blue", "Red", "Red", "Red", 
      "Red", "Blue", "Blue") 
value <- sample(1:10, 12, replace = TRUE) 
df <- cbind.data.frame(date, colour, value) 
df <- xts(df[,-1], order.by = df$date) 

これは次のようになりますサンプルデータフレームを作成します。私の質問を説明するために、以下を参照してください

私に与える:

   value 
2015-01-30 2.000000 
2015-03-22 9.000000 
2015-08-13 5.000000 
2015-09-01 8.000000 
2015-11-10 7.000000 
2016-04-26 2.000000 
2016-07-08 5.666667 
2016-10-01 6.000000 
2016-11-07 2.000000 

しかし、(この場合は)色変数を集計する方法はよくわかりません(月ごとに各色の合計が必要です)。どんな助けでも大歓迎です。

答えて

1

これはいかがですか?

# You can replace the format with the following to get a year month object 
zoo::as.yearmon(index(df)) 

# Or you can covert to date by using the first of every month 
as.Date(paste(format(index(df), "%Y-%m"), "-01", sep = "")) 

あなたが現在より多くのアイデアを見つけるかもしれない:Converting year and month ("yyyy-mm" format) to a date in R?

+0

非常に役立つ@NBATrends Thiクラスの「文字」変数である「月」変数を作成します。出力がクラス「日付」のままであることを保証する方法はありますか?私は 'as.Date(df $ Month、format ="%Y-%m ")'を試しましたが、役に立たない。あなたの助けに感謝。 – drgregmartin

2

あなたは色によってサブセット化後のXTSオブジェクトを操作したい場合は、それが動作するのは簡単です下のあなたのコメントに応えて

aggregate(as.numeric(df$value), 
      list(Month = format(index(df), "%Y-%m"), 
       Colour = df$colour), 
      mean) 

それぞれの時系列(色別)を次のようなリストに分けて表示します。

df <- cbind.data.frame(date, colour, value) 

> class(df) 
#[1] "data.frame" 

# data.frame split (not xts split) to separate data by colour in a list object: 
l_out <- split(df, colour) 

> class(l_out[[1]]) 
[1] "data.frame" 

mthly_mean <- function(x) { 
    apply.monthly(as.xts(x[, "value"], x[, "date"]), mean)  
} 

# Each element in the list is an xts object (not a data.frame) containing the mean of the data for each month: 
l_res <- lapply(l_out, FUN = mthly_mean) 
# or more succinctly: 
# l_res <- lapply(l_out, FUN = function(x) apply.monthly(as.xts(x[, "value"], x[, "date"]), mean)) 

> l_res 
# $Blue 
# [,1] 
# 2015-01-15 8.0 
# 2015-07-21 4.5 
# 2016-01-28 5.0 
# 2016-04-28 4.0 
# 2016-05-08 2.0 
# 
# $Red 
# [,1] 
# 2015-11-30 3 
# 2016-01-18 7 
# 2016-02-25 5 
# 2016-04-17 1 
# 2016-05-23 6 
# 2016-07-14 5 

> class(l_res[[1]]) 
[1] "xts" "zoo" 
関連する問題