基本語法:for (name in expr_1) expr_2
實例操作:
1.構造矩陣
x=array(0,dim=c(4,4)) # 構造四階矩陣 數值全為0 for (i in 1:4){ for (j in 1:4){ x[i,j]=1/(i+j+1) } } print(x)
[,1] [,2] [,3] [,4] [1,] 0.3333333 0.2500000 0.2000000 0.1666667 [2,] 0.2500000 0.2000000 0.1666667 0.1428571 [3,] 0.2000000 0.1666667 0.1428571 0.1250000 [4,] 0.1666667 0.1428571 0.1250000 0.1111111
2.利用循序進行單位根檢驗
nrow=20 ncol=5 A=matrix(nrow=nrow,ncol=ncol,data=NA)
for (i in 1:ncol) { A[,i]= rnorm(20, mean=0, sd=1) #構造正太分布,產生20個隨機數,服從正太分布 }
library(tseries) #導入所需要的函數包 for (i in 1:5) {print(adf.test(A[,i]))} #AD
結果如下,很方便.
Augmented Dickey-Fuller Test data: A[, i] Dickey-Fuller = -2.4773, Lag order = 2, p-value = 0.3905 alternative hypothesis: stationary Augmented Dickey-Fuller Test data: A[, i] Dickey-Fuller = -1.8836, Lag order = 2, p-value = 0.6167 alternative hypothesis: stationary Augmented Dickey-Fuller Test data: A[, i] Dickey-Fuller = -3.5647, Lag order = 2, p-value = 0.05491 alternative hypothesis: stationary Augmented Dickey-Fuller Test data: A[, i] Dickey-Fuller = -2.2957, Lag order = 2, p-value = 0.4597 alternative hypothesis: stationary Augmented Dickey-Fuller Test data: A[, i] Dickey-Fuller = -2.2784, Lag order = 2, p-value = 0.4663 alternative hypothesis: stationary
F單位根檢驗