将数据帧转换为时间序列R

时间:2019-08-23 08:40:24

标签: r time-series

我有以下数据

select a.Id,a.patientId,count(a.patientId), a2.IdCount
from A a
left join (select Id, count(Id) as "IdCount"
            from A
            group by Id) a2
        on a.Id = a2.Id
group by a.Id,a.patientId, a2.IdCount

我需要转换为时间序列进行预测

data_sample
        date         Sum 
1  Feb 2015      3322.01 
2  Mar 2015      6652.77 
3  Apr 2015      3311.12 
etc

4 个答案:

答案 0 :(得分:2)

如果要使用as.Date(),则必须指定完整日期。 只需在每个条目的末尾添加01。

date <- c("Feb 2015", "Mar 2015", "Apr 2015")
date <- as.Date(paste(date, "01"), format="%b %Y %d")

您可以按如下方式将它们转换回

format(date, "%b %Y")

或使用动物园图书馆的as.yearmon

library("zoo")
as.yearmon(date)

此处有一些示例:Converting Date formats in R

答案 1 :(得分:1)

R具有表示时间序列的多种方式。由于您仅使用日期和总和,因此我为您创建了一个示例时间序列。我选择随机的日期和数字。

致电包裹

 > data <- xts(data_sample[,-1], order.by=as.Date(data_sample[,1], "%Y %m"))
Error in 1 - frac : non-numeric argument to binary operator
> data <- xts(data_sample[,-1], order.by=as.Date(data_sample[,1], "%m %Y"))
Error in 1 - frac : non-numeric argument to binary operator



> ts_ts(ts_long(data_sample))
Error in guess_time(x) : 
  No [time] column detected. To be explict, name time column as 'time'.

创建数据框

library(xts)
data_sample <- data.frame(
        date = as.Date(c("2012-01-01","2013-01-01","2014-01-01", )),  
        sum1 = c(3322.01, 6652.77, 3311.12))

按照R可以理解的格式转换日期。

head(data_sample)

绘制图形

rdate<- as.Date(data_sample$date, "%m/%d/%y")  
fix(rdate)

执行上述代码将得到以下输出。

enter image description here

答案 2 :(得分:1)

假设data_sample如末尾的注释中所示,可重复使用read.zoo转换为类Zoo的时间序列,然后以该形式使用它或将其转换为其他类,例如使用适当的as。*函数作为xts或ts。在这里,我们使用yearmon类来表示索引,因为它直接表示年和月,没有日。此类将在Zoo和xts中使用,转换为ts时将进行适当的转换。

library(xts) # this also loads zoo

z <- read.zoo(data_sample, FUN = as.yearmon, format = "%b %Y")

as.xts(z)
as.ts(z)

日期

也可以将Date类用于Zoo和xts中的索引,但这不适用于ts类。使用Date类意味着连续点之间的距离根据每月的天数而变化,而不是规则间隔的序列,因此使用Date作为月度数据通常对预测没有用。

zd <- aggregate(z, as.Date, c)
xd <- as.xts(zd)

注意

以可复制的形式输入

Lines <- "date,Sum 
1,Feb 2015,3322.01 
2,Mar 2015,6652.77 
3,Apr 2015,3311.12 "
data_sample <- read.csv(text = Lines)

答案 3 :(得分:0)

air1 <- type.convert(.preformat.ts(AirPassengers))
airpassengers <- as.data.frame(air1)
 
 View(airpassengers)
 class(airpassengers)
[1] "data.frame"

它将时间序列数据转换为数据帧。

相关问题