[R] Storing loop output from a function

Martin Maechler maechler at stat.math.ethz.ch
Mon Nov 29 09:32:12 CET 2004


>>>>> "UweL" == Uwe Ligges <ligges at statistik.uni-dortmund.de>
>>>>>     on Sat, 27 Nov 2004 17:09:26 +0100 writes:

    UweL> Andrew Kniss wrote:
    >> I am attempting to write an R function to aid in time series diagnostics.
    >> The tsdiag() works well, but I would prefer to get a plot with ACF, PACF,
    >> and Ljung-Box p-values of residuals.  In my attempt to get to that point, I
    >> am writing a function to calculate Ljung-Box p-values for residuals at
    >> various lag distances.
    >> 
    >> ljung <- function(fit) 
    >>   for(i in c(1:24,36,48))   
    >>    {box<-(Box.test(fit$residuals, lag=i, type="Ljung-Box")) 
    >>     print(c(i, box$p.value))}
    >> 

    UweL> You need to return() rather than print() the object.

and Andy Liaw correctly remarked that

    AndyL> Yes, but print() is supposed to return (invisibly) its argument(s)...

Yes.
But I'm pretty sure, Andrew's problem is to get all the p-values back
from his function and not just the last one

Which -- (together with making 'lags' a function argument)
would be something like

    ljung <- function(fit, lags = c(1:24,36,48)) 
    {
	nl <- length(lags)
        r <- numeric(nl)
	for(i in 1:nl)
	   r[i] <- Box.test(fit$residuals, lag= lags[i], type="Ljung-Box")
        r
    }

or, simply, more elegantly and efficiently, 
but a bit harder to understand for a beginner,

    ljung <- function(fit, lags = c(1:24,36,48)) 
        sapply(lags, function(ll) 
               Box.test(fit$residuals, lag = ll, type="Ljung-Box"))

Martin Maechler, ETH Zurich




More information about the R-help mailing list