R中时间序列分析-趋势分析Trend

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lll1528238733/article/details/76033910

趋势分析(Trend)

常用趋势的数学函数
线性函数 y=ax+b
指数函数 y=a^x
二次函数 y=ax^2+bx+c

曲线拟合方法
nls可以拟合任意表达式的曲线

nls(formula,start,data)

  • formula 曲线表达式
  • start 参数的初始点,可以随便设置一个
    设置这个参数的目的:(减少递归的次数,加快运算的速度)
  • data 需要拟合的数据
data <- read.csv("data.csv", fileEncoding="UTF8")
#data <- read.csv("data.csv", fileEncoding="UTF8", stringsAsFactors=FALSE)

datas <- split(data, data$广告商)

par(mfrow=c(1, 1))

plot(
  data$销售量
)

datas[[1]]$month <- 1:12

data.model <- nls(
  销售量 ~ A*month + B, 
  start=list(A=1, B=1), 
  data=datas[[1]], 
  trace=T
)

lines(
  datas[[1]]$month, 
  17.36*datas[[1]]$month + 174.14
)

data.model <- nls(
  销售量 ~ A^month, 
  start=list(A=1), 
  data=datas[[1]], 
  trace=T
)

lines(
  datas[[1]]$month, 
  1.685^datas[[1]]$month
)


data.model <- nls(
  销售量 ~ A*month^2 + B*month + C, 
  start=list(A=1, B=1, C=1), 
  data=datas[[1]], 
  trace=T
)

lines(
  datas[[1]]$month, 
  -0.1469*datas[[1]]$month^2 + 19.2727*datas[[1]]$month + 169.6818 
)

这里写图片描述

猜你喜欢

转载自blog.csdn.net/lll1528238733/article/details/76033910
今日推荐