Search code examples
rloopsfor-loopformatcbind

R: Formatting loop output - without repeated column names?


I use following script to output the results for serial correlation:

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 is the number of lags I am testing for, as the data is quarterly data. The function

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

returns

  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

Is there any way to avoid re-printing the column titles and rows? My desired output:

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

Thanks you for your help!


Solution

  • The following does what you want.

    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