UNIVERSIDAD NACIONAL AUTONOMA DE MEXICO
Series de tiempo
Marisol Arreola Silva
require(dplyr)
require(gganimate)
library("gridExtra")
library(ggfortify)
trend_sta<-function(time_serie){
medias<-c()
n<-length(time_serie)
stp<-floor(n/11)
for (i in 1:floor(length(time_serie)/stp)) {
medias[i]=mean(time_serie[(stp*(i-1)):(stp*i)]%>% t() %>% as.vector(), na.rm = 1)
}
f<-approxfun(x=seq(from=1, to=n, by=stp)[-(stp-1)], y=medias)
m<-f(1:n)
nuevo<-(time_serie-m)
df<-data.frame(time_serie)
df1<-data.frame(nuevo)
time<-1:n
linear_reg<-lm(1:n~time_serie, time_serie)
slope<-linear_reg$coefficients[2]
trend=""
if(slope<0){trend= "negative trend"}else{trend="positive trend"}
bxp<-ggplot(df, aes(time, time_serie)) + geom_line() + stat_smooth(method = lm)+ annotate("text", x = 17, y = max(time_serie)-max(time_serie)/30, label = paste("slope:", slope))+annotate("text", x = 15, y = max(time_serie)-max(time_serie)/10, label = paste(trend))
dp<-ggplot(df1, aes(time, nuevo, col=3)) + geom_line()
grid.arrange(bxp, ncol = 1, nrow = 1)
ggplot(df1, aes(time, nuevo)) + geom_line()+transition_reveal(time)
}
trend_sta(AirPassengers)
trend_sta(BJsales)
trend_sta(WWWusage)