Anubhav Dikshit
Anubhav Dikshit

Reputation: 1829

Applying Time series models for each row

I have a dataframe (df), which is wide dataset with the following structure,

ID 2015/01/01 2015/02/01 2015/03/01 2015/04/01
A1 42         42        24          32 
A2 22         22        24          32 
A3 12         15        19          22 
A4 8          12        18          24 

I tired the following:

ts_1 <-  ts(df[1:1,], start = c(2015, 05), frequency = 12)

ts_1_stl <- stl(ts_1, s.window = "periodic")

But I got the error as :

Error in stl(ts_1, s.window = "periodic") : only univariate series are allowed

Upvotes: 1

Views: 658

Answers (1)

akrun
akrun

Reputation: 887811

If we are applying on each row (the first column is 'ID', a character class column, which is not needed), we can use apply with MARGIN = 1

apply(df[-1], 1, FUN = function(x) ts(x, start = c(2015, 05), frequency = 12))

For the whole dataset, we need to unlist

ts(unlist(df[-1]), start = c(2015, 05), frequency = 12)

We would assume the 'df' to have more number of columns to have enough observations i.e. at least 2 periods for the "periodic" to work

set.seed(24)
df <- cbind(Col1 = LETTERS[1:4], as.data.frame(matrix(rnorm(31*4), ncol=31)))
res <- apply(df[-1], 1, FUN = function(x) stl(ts(x, start = c(2015, 05),
           frequency = 12), s.window = "periodic"))

Upvotes: 1

Related Questions