Tenemos que hacer una función que nos diga cuál es la tendencia de una serie de tiempo, usaremos a los parámetros: serie y k.
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
tendencia <- function(serie,k){
if(class(serie) == "ts"){
serie_num <- as.numeric(serie)
mm <- c()
for (i in 1:floor(length(serie_num)/k)) {
mm[i] <- mean(serie_num[(k*(i-1)):(k*i)] %>% t() %>% as.vector(),
na.rm = T)
}
if(mm[1] < mm[length(mm)]){
tendencia <- "La tendencia de la serie es creciente"
}else if(mm[1] > mm[length(mm)]){
tendencia <- "La tendencia de la serie es decreciente"
}else{
tendencia <- "La tendencia de la serie es constante"
}
g1 <- ggplot() +
geom_line(aes(x=c(1:length(serie_num)), y=serie_num), color = "#653AAD") +
geom_smooth(aes(x = seq(from = round(k/2), to = length(serie_num), by = k), y = mm), color = "#BC1863") +
geom_point(aes(x = c(1:length(serie_num)), y = serie_num)) +
labs(x = "Tiempo", y = "Observaciones", title = "Serie de Tiempo con Medias Moviles") + theme_bw()
return(list(g1, tendencia))
}else{
stop('class(s1) is not ts')
}
}
Usando el dataset de AirPassangers nos quedan los siguientes plots.
tendencia(AirPassengers,14)
## [[1]]
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
##
## [[2]]
## [1] "La tendencia de la serie es creciente"
tendencia(AirPassengers,102)
## [[1]]
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
##
## [[2]]
## [1] "La tendencia de la serie es constante"
tendencia(AirPassengers,10)
## [[1]]
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
##
## [[2]]
## [1] "La tendencia de la serie es creciente"