简体   繁体   English

将数据帧转换为 r 中的时间序列

[英]Transforming data frame to time series in r

I am currently trying to convert a data.frame to a time series.我目前正在尝试将 data.frame 转换为时间序列。 The data frame looks like this:数据框如下所示:

Data Frame

All I want to do is be able to plot the doc data as a function of time and run a statistical test on it.我想要做的就是能够将文档数据绘制为时间的函数并对其进行统计测试。

Any help would be greatly appreciated!任何帮助将不胜感激!

This is what my code currently looks like:这是我的代码目前的样子:

x=aggregate( doc ~ mo + yr , B , mean )
x$Date <- as.yearmon(paste(x$yr, x$mo), "%Y %m")
df_ts <- xts(x, order.by = x$Date)
keeps <- "doc"
df_ts <- df_ts[ , keeps, drop = FALSE]
df_ts_1 <- as.ts(df_ts, start = head(index(df_ts), 1), end = 
tail(index(df_ts), 1))

The issue I'm running into is that the months and years are not in sequential order so when I try to apply a as.tf function, the data does not fill in correctly.我遇到的问题是月份和年份不是按顺序排列的,所以当我尝试应用 as.tf 函数时,数据没有正确填写。

Using DF defined reproducibly in the Note at the end read the data frame into a zoo object converting the Date column to yearmon class and plot using ggplot2.在最后的注释中使用可重复定义的DF将数据框读入动物园对象,将Date列转换为yearmon类并使用 ggplot2 绘图。 If there exist duplicate dates (there are none in the example data) then add the aggregate = mean argument to read.zoo .如果存在重复的日期(示例数据中没有),则将aggregate = mean参数添加到read.zoo

library(ggplot2)
library(zoo)

z <- read.zoo(DF[c("Date", "doc")], FUN = as.yearmon, format = "%b %Y")
autoplot(z) + scale_x_yearmon()

This would also work:这也可以:

tt <- as.ts(z)
plot(na.approx(tt), ylab = "tt")

Note笔记

In the future please do not use images.以后请不要使用图像。 I have retyped the first three rows this time.这次我重新输入了前三行。

DF <- data.frame(month = c("02", "10", "12"), year = c(1998, 2000, 2000),
 doc = c(1.55, 2.2, 0.96), Date = c("Feb 1998", "Oct 2000", "Dec 2000"),
 stringsAsFactors = FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM