How to convert a dataframe in time-series ?

Hello everyone,

I am very new to R software and i have to analyze a time-serie corresponding to the number of cases per day, from april, 2020 to the 1st of january 2021. In order to study acf and pacf ( Partial autocorrelation function) of the serie, i need first to convert it into time serie but for now i only have a dataframe (see below a sample). I am a bit lost with all the codes i read about the conversion (since it is for specific cases). If someone can help me with my case, i will be grateful.
Thank you in advance,
Aline

ps : sorry for my english

There are some awesome packages for working with time data. Try this:

library(tidyverse)
library(lubridate)
library(xts)

my_datatable <- tribble(
  ~admissions,  ~ Date,
  151,          '2020-03-19',
  89,            '2020-03-20',
  104,          '2020-03-21',
  125,          '2020-03-22',
  155,          '2020-03-23'
) %>% 
  mutate(Date = ymd(Date))

my_date_info <- my_datatable %>% pull(Date)


my_time_series_data <- my_datatable %>% 
  xts(x = ., order.by = my_date_info)

Then you can graph your data with something like:

library(dygraphs)
my_time_series_data[,'admissions'] %>% dygraph()

And run an acf or pacf like:

pacf(my_datatable[,'admissions'])

It is not at all obvious, but a time series does not require a date column unless there are gaps.

For the sample data

series <- ts(my_datatable$admissions, start = c(2020,3,19), frequency = 365)

Thank you so much for your help, it works well !

Yes, my dataframe does not have gaps so i tried your code and it worked too, thank you !

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.