Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a List of TimeSeries from a dataframe

I have a dataframe that looks like this:

# A tibble: 6 x 4
# Groups:   IND_LOC [1]
  year_month    total_this_month mean_this_month IND_LOC
  <S3: yearmon>            <dbl>           <dbl> <fct>  
1 Jan 2013              3960268.         360024. 8_9    
2 Feb 2013              3051909.         277446. 8_9    
3 Mar 2013              3504636.         318603. 8_9    
4 Apr 2013              3234451.         294041. 8_9    
5 May 2013              3409146.         284096. 8_9    
6 Jun 2013              3619219.         301602. 8_9 

The last column 'IND_LOC' has 89 unique values (1_1, 1_2 ... 8_9)

I would like to generate a list of timeseries corresponding to these 'IND_LOC' values such that it has the following structure (this is just an example with a different dataset, substituting '$1_1' for '$Germany' etc.):

> str(time_series)
List of 9
 $ Germany    : Time-Series [1:52] from 1960 to 2011: 684721 716424 749838   ...
 $ Singapore  : Time-Series [1:52] from 1960 to 2011: 7208 7795 8349   ...
 $ Finland    : Time-Series [1:37] from 1975 to 2011: 85842 86137 86344   ...

Any help with this is greatly appreciated!

like image 422
Davide Lorino Avatar asked Jan 03 '23 09:01

Davide Lorino


2 Answers

Another option, using split and lapply; and using zoo as a helper to convert to ts.

dat <- read.csv(text="year_month,total_this_month,mean_this_month,IND_LOC
Jan 2013,3960268,360024,8_9
Feb 2013,3051909,277446,8_9
Mar 2013,3504636,318603,8_9
Apr 2013,3234451,294041,8_9
May 2013,3409146,284096,8_9
Jun 2013,3619219,301602,8_9
Jan 2013,3960268,360024,9_9
Feb 2013,3051909,277446,9_9
Mar 2013,3504636,318603,9_9
Apr 2013,3234451,294041,9_9
May 2013,3409146,284096,9_9
Jun 2013,3619219,301602,9_9")
dat$year_month <- as.yearmon(dat$year_month)

library(zoo)
time_series <- lapply(split(dat, dat$IND_LOC),
  function(x) as.ts(zoo(x$total_this_month, x$year_month)))
str(time_series)
# List of 2
#   $ 8_9: Time-Series [1:6] from 1 to 6: 3234451 3051909 3960268 3619219 3504636
#   $ 9_9: Time-Series [1:6] from 1 to 6: 3234451 3051909 3960268 3619219 3504636
sapply(time_series, frequency)
# 8_9 9_9
#  12  12
like image 88
Joshua Ulrich Avatar answered Jan 13 '23 13:01

Joshua Ulrich


We could do a group by and summarise

library(dplyr)
library(lubridate)
df %>%
  group_by(IND_LOC) %>%
  summarise(time_series = list(ts(total_this_month, 
       start= c(year(year_month[1]), month(year_month[1])), frequency = 12)))  
like image 28
akrun Avatar answered Jan 13 '23 12:01

akrun