「zoo」ライブラリを使用してRに時系列をロードしようとしています。
私の観測はさまざまな精度を持っています。日/月/年を持つものもあれば、月と年のみを持つものもあれば、年を持つものもあります。
02/10/1915
1917
07/1917
07/1918
30/08/2018
その後、年、年、月ごとに行を集計する必要があります。基本的な R の as.Date 関数はそれを処理しません。このデータを動物園でモデル化するにはどうすればよいですか?
ありがとう、ムロン
質問のインデックス データとそれに続く数字から形成されたテスト データを使用します。
# test data
Lines <- "02/10/1915 1
1917 2
07/1917 3
07/1918 4
30/08/2018 5"
年次集計
library(zoo)
to.year <- function(x) as.numeric(sub(".*/", "", as.character(x)))
read.zoo(text = Lines, FUN = to.year, aggregate = mean)
最後の行は次を返します。
1915 1917 1918 2018
1.0 2.5 4.0 5.0
年月集計
月のないデータの年月集計は意味がないため、最初に年のみのデータを削除し、残りを集計します。
DF <- read.table(text = Lines, as.is = TRUE)
# remove year-only records. DF.ym has at least year and month.
yr <- suppressWarnings(as.numeric(DF[[1]]))
DF.ym <- DF[is.na(yr), ]
# remove day, if present, and convert to yearmon.
to.yearmon <- function(x) as.yearmon( sub("\\d{1,2}/(\\d{1,2}/)", "\\1", x), "%m/%Y" )
read.zoo(DF.ym, FUN = to.yearmon, aggregate = mean)
最後の行は次のとおりです。
Oct 1915 Jul 1917 Jul 1918 Aug 2018
1 3 4 5
更新: 簡素化