与zoo在R的处理时间

与zoo在R的处理时间,r,date,zoo,R,Date,Zoo,我正试图用“动物园”库在R中加载时间序列 我的观察结果精度各不相同。有些具有日/月/年,有些仅具有月和年,而有些具有年: 02/10/1915 1917 07/1917 07/1918 30/08/2018 随后,我需要按年份、年份和月份汇总这些行。 基本的R as.Date函数不能处理这个问题。 如何使用zoo对这些数据进行建模 谢谢, Mulone我们使用由问题中的索引数据形成的测试数据,后跟一个数字: # test data Lines <- "02/10/1915 1 1917

我正试图用“动物园”库在R中加载时间序列

我的观察结果精度各不相同。有些具有日/月/年,有些仅具有月和年,而有些具有年:

02/10/1915
1917
07/1917
07/1918
30/08/2018
随后,我需要按年份、年份和月份汇总这些行。 基本的R as.Date函数不能处理这个问题。 如何使用zoo对这些数据进行建模

谢谢,
Mulone

我们使用由问题中的索引数据形成的测试数据,后跟一个数字:

# 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)
由于无月数据的年/月聚合毫无意义,我们首先放弃仅年数据,然后聚合其余数据:

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)

更新:simplifications

对于没有月份的数据,您如何按月聚合?我将排除它。有一个简单的解决方案,包括创建三个单独的字段,并以不同的方式对待它们,但我想知道zoo是否有一些功能来做到这一点。
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