2017-09-04 49 views
1

我用下面的腳本輸出序列相關的結果:R:格式化循環輸出 - 沒有重複列名?

serial = function(x,y,z){ 
    for (i in 1:4) { 
    table_serial <- data.frame(i, 
    serial.test(VAR(cbind(x,y),p=i,type="const"),lags.pt=4, type=z)$serial$statistic[[1]],     
    serial.test(VAR(cbind(x,y),p=i,type="const"),lags.pt=4, type=z)$serial$p.value[[1]], digits=3)) 
    colnames(output) <- c("Lag", "Chi", "p") 
    print(data.frame(serial)) 
    } 
} 

lags.pt=4是滯後,我測試的數,因爲數據是季度數據。功能

serial(data[1],data[2], "PT.asymptotic") 

回報

Lag Chi p 
1 1 41.46 0.581 
    Lag Chi p 
1 2 50.032 0.133 
    Lag Chi p 
1 3 40.097 0.293 
    Lag Chi p 
1 4 40.582 0.142 

有什麼辦法,以避免重新打印的列標題和行? 我的理想輸出:

Lag Chi p 
1 41.46 0.581 
2 50.032 0.133 
3 40.097 0.293 
4 40.582 0.142 

感謝您的幫助!

回答

1

以下是你想要的。

serial = function(x,y,z){ 
    table_serial <- data.frame() 
    for (i in 1:4) { 
     s1 <- serial.test(VAR(cbind(x,y), p=i, type="const"), lags.pt=4, type=z)$serial$statistic[[1]] 
     s2 <- serial.test(VAR(cbind(x,y), p=i, type="const"), lags.pt=4, type=z)$serial$p.value[[1]] 
     table_serial <- rbind(table_serial, c(i, s1, s2)) 
    } 
    colnames(table_serial) <- c("Lag", "Chi", "p") 
    table_serial 
} 

# test it 
set.seed(1234) # make it reproducible 
serial(rnorm(100), rnorm(100), "BG") 
    Lag  Chi   p 
1 1 13.76826 0.8420485 
2 2 27.77865 0.1147436 
3 3 17.09634 0.6467093 
4 4 13.58514 0.8508920