简体   繁体   中英

R Language, how to create a timeseries from dataframe with datetime and value columns

I have a simple data frame, observations_df , with two columns DateTime and Value :

2002-03-28T19:30:00, 23.53, ...

How to create a time series from data frame observations_df and show time series in graph?

Tutorials are very rich and complex.I have tried different approaches unsuccessfully.

Does this answer your question?

library(tidyverse)

df <- tibble(
  date = Sys.Date() + 0:10,
  value = runif(n = 11)
)

df %>%
  ggplot(aes(x = date, y = value)) +
  geom_line()

First you may use ts to create a time series "ts" object.

dat.ts <- ts(dat[,2], start=dat[1,1], end=dat[nrow(dat),1])
# Time Series:
# Start = 18263 
# End = 18292 
# Frequency = 1 
# [1] 0.16804153 0.80751640 0.38494235 0.32773432 0.60210067 0.60439405 0.12463344 0.29460092
# [9] 0.57760992 0.63097927 0.51201590 0.50502391 0.53403535 0.55724944 0.86791949 0.82970869
# [17] 0.11144915 0.70368836 0.89748826 0.27973255 0.22820188 0.01532989 0.12898156 0.09338193
# [25] 0.23688501 0.79114741 0.59973157 0.91014771 0.56042455 0.75570477

Then, actually there is a plot method and you could just do plot(dat.ts) . However, "ts" objects store dates numerically, and we want to read "real" dates on the x-axis and therefore probably want to do a manual axis labeling with somewhat "thinned out" elements from the date column using eg modulo %% .

labs <- dat$datetime[as.numeric(substr(dat$datetime, 9, 10)) %% 7 == 0]

plot(dat.ts, xaxt="n", main="My Title", col=2, xlab="time", ylab="value")
axis(1, labels=F, at=dat$datetime, tck=-.01)
axis(1, labels=F, at=labs, tck=-.03)
mtext(as.character(labs), 1, 1, at=labs)
legend("topleft", lty=1, legend="time series xy", col=2)

在此处输入图像描述


Toy data used

set.seed(3)
dat <- data.frame(datetime=as.Date(seq(1:30), "2020-01-01"),
                  value=runif(30))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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