2017-07-25 39 views
-1

我有一个大约有160个数据点的矩阵。我有兴趣了解该系列的任何部分(不必是整个系列)是否具有趋势(线性和增加/减少)。我只想找出线性趋势而不是非线性趋势。如何找到R中的线性趋势?

我会通过测试它的形式的基本数据集开始:

A<-c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 
16,17,17,18,17,17,18,17,17,18,19,19,19,19,19,19,19,19,19,19,19) 

这里仅通过绘图数据,我认为这种趋势是向上的,从1:17我会想为此引入假人(一旦我知道趋势的起点和终点,我将能够做到这一点)。有什么方法可以知道吗? IN R?

+0

找到你需要至少2个变量的线性趋势。我们应该如何看待你的矢量趋势?从1到19将呈现增长趋势,将其从19降至1将呈现下降趋势。 –

+0

我不太确定你的意思是2变量。在时间序列中,趋势只计算在一个变量上,而不是两个。 –

+0

我相信时间序列是绘制在时间和频率之间。在这里看到两个变量。 –

回答

0

检查lm功能。此功能可帮助您创建线性回归。

A<-c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,17,18,17,17,18,17,17,18,19,19,19,19,19,19,19,19,19,19,19) 
x = c(1:length(A)) 
plot(x,A) 
reg = lm(A~x) 
abline(reg,col="red") 

Linear regression

如果你想在的startPoint启动线性回归,用'A [的startPoint:长度(A)]

而且知道的趋势:print(reg)

+0

但是这个趋势线是针对整个数据集的,对吗? –

+0

我想让R预测是否存在线性趋势,如果是,那么从哪个点到哪个点。所以我可以添加一个虚拟的相同。 –

+0

所以看'摘要(reg)'。这可以帮助您知道是否存在线性趋势,或者是否有p值(** Pr(> | t |)**)。 x行的值需要小于2e-16 –

0

分解函数可以帮助。假人可能不够敏感。您可能只想减去趋势组件。尝试:

A<-c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 
16,17,17,18,17,17,18,17,17,18,19,19,19,19,19,19,19,19,19,19,19) 

# convert to ts first 
my.ts <- ts(A, start = c(2000, 1), freq = 12) # .. if you have months 
my.trend <- decompose(my.ts)$trend 
print(max(diff(my.trend), na.rm = TRUE)) 

# use a certain percentage of max difference to find start and end of trend 
tolerance <- 0.1 # say 10 % .. 
trend.start <- which.max(my.trend >= tolerance * max(my.trend, na.rm=T)) 
trend.end <- which.max(my.trend >= (1-tolerance) * max(my.trend, na.rm=T)) 

# plot shows that it - almost - fits 
plot(my.ts, col = "blue", type = "o") 
abline(v = time(my.ts)[trend.start], col = "gray") 
abline(v = time(my.ts)[trend.end], col = "gray") 
lines(my.trend) 

# but what do you do, if you have a ts like this .. 
B <- c(rep(0,50), seq(1,30,0.5), rep(30,50), seq(30,1,-1)) + rnorm (189,0,1) 
my.ts <- ts(B, start = c(2000, 01), freq = 12) 
plot(my.ts) 
my.trend <- decompose(my.ts)$trend 
plot(my.trend) 
+0

先生,这工作很好,但我不太确定这里发生了什么 –

+0

先生,一个问题,如果我有每周数据,我该如何介绍频率?我有3年的数据和每周。我也有这些数据点的日期。 –

+0

在你答案的最后部分,你可以看到你的方法只检测到一个上升趋势?另外,你说过使用一定比例的最大差异,但你没有使用它,只是用最大值乘以容差水平? –

1
A<-c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 
    16,17,17,18,17,17,18,17,17,18,19,19,19,19,19,19,19,19,19,19,19) 
x <- seq_along(A) 

plot(A ~ x) 

fit0 <- lm(A ~ x) 

library(segmented) 
fit1 <- segmented(fit0, seg.Z = ~ x, psi = list(x = c(10, 40))) 
summary(fit1) 
#Estimated Break-Point(s): 
#   Est. St.Err 
#psi1.x 18.00 0.220 
#psi2.x 34.04 0.246 


lines(x, predict(fit1), col = "red") 

resulting plot

+0

先生,这是多种趋势? –