Home > Mobile >  Time series - Convert every column of dataframe to time series
Time series - Convert every column of dataframe to time series

Time:01-11

I have a dataframe df in R:

month  abc1   def2   xyz3
201201    1      2      4 
201202    2      5      7
201203    4     11      4
201204    6     23     40

I would like to convert each of the columns (of which there are ~50, each with ~100 monthly observations) to a time series format in order to check for seasonality in the data, using the decompose function.

I assumed a for loop using the ts function would be the best way of doing this. I would like to use something along the lines of the loop below, although I realise using a function on the left side of the <- produces an error. Is there a way to dynamically name variables generated by a loop?

for(i in 2:ncol(df)) {
  paste(names(df[, i]), "_ts") <- ts(df[ ,i], start = c(2012, 1), end = c(2021,11), frequency = 12)
}

CodePudding user response:

You could try zoo:

test = data.frame(month=c("201201", "201202", "201203", "201204"), abc1=c(1,2,3,4), def2=c(4,6,7,10), xyz3=c(12,15,16,19))

library(zoo)

ZOO =zoo(test[, c("abc1", "def2", "xyz3")], order.by=as.Date(paste0(test$month, "01"), format="%Y%m%d"))

ts(ZOO, frequency=12)

Output:

      abc1 def2 xyz3
Jan 1    1    4   12
Feb 1    2    6   15
Mar 1    3    7   16
Apr 1    4   10   19
attr(,"index")
[1] 2012-01-01 2012-02-01 2012-03-01 2012-04-01

Update: Now with correct frequency.

  •  Tags:  
  • Related