apis_mellifera_2023
apis_mellifera_2023

Reputation: 11

Seasonal Adjustment of columns within dataframe

I have a dataframe that contains monthly data on natural gas and oil in storage and CDD/HDD (as part of a larger class project on modeling gas and oil prices). I want to seasonally adjust these 4 columns since the data is seasonal. I am new to R and still am getting use to the logic.

I have tried this

install.packages("seasonal")
library(seasonal)
data%>%
    mutate(`sNG Stored` <- seas(`NG Stored`,x11 = ""))

and the following error was thrown:

Error in `mutate()`:
ℹ In argument: ``sNG Stored` <- seas(`NG Stored`, x11 = "")`.
Caused by error in `x13_prepare()`:
! 'x' argument is not a time series.

Upvotes: 1

Views: 129

Answers (1)

ncraig
ncraig

Reputation: 1203

According to documentation, the function seasonal::seas() takes as x one of the following types of objects: ts, mts, or a list of ts objects. Based on the error you report, the datafreame column NG Stored is not a time series object. For the seas() function to run properly, the column NG Stored needs to be converted to either a ts or mts. Your question didn't supply any data, so I created some toy data to illustrate one possible conversion process.

library(zoo)
#> Warning: package 'zoo' was built under R version 4.2.3
#> 
#> Attaching package: 'zoo'
#> The following objects are masked from 'package:base':
#> 
#>     as.Date, as.Date.numeric

df <- data.frame(date = as.Date('2022-01-01') + 0:9,
                 values = runif(10, 10, 500) + seq(50, 59)^2)
df
#>          date   values
#> 1  2022-01-01 2519.030
#> 2  2022-01-02 2983.906
#> 3  2022-01-03 2742.768
#> 4  2022-01-04 2998.628
#> 5  2022-01-05 2999.749
#> 6  2022-01-06 3149.857
#> 7  2022-01-07 3468.573
#> 8  2022-01-08 3522.451
#> 9  2022-01-09 3827.004
#> 10 2022-01-10 3716.138
str(df)
#> 'data.frame':    10 obs. of  2 variables:
#>  $ date  : Date, format: "2022-01-01" "2022-01-02" ...
#>  $ values: num  2519 2984 2743 2999 3000 ...
tseries <- read.zoo(df)
str(tseries)
#> 'zoo' series from 2022-01-01 to 2022-01-10
#>   Data: num [1:10] 2519 2984 2743 2999 3000 ...
#>   Index:  Date[1:10], format: "2022-01-01" "2022-01-02" "2022-01-03" "2022-01-04" "2022-01-05" ...
class(tseries)
#> [1] "zoo"
tseries_ts <- as.ts(tseries)
class(tseries_ts)
#> [1] "ts"

Now the dataframe should be ready to accept the seas() function. The base R functions str() and class() are helpful for diagnosing these kinds of issues.

Upvotes: 0

Related Questions