[R] incomplete function output

Sundar Dorai-Raj sundar.dorai-raj at PDF.COM
Wed Oct 13 19:30:48 CEST 2004



bogdan romocea wrote:
> Dear R users,
> 
> I have a function (below) which encompasses several tests.
> However, when I run it, only the output of the last test is
> displayed. How can I ensure that the function root(var)
> will run and display the output from all tests, and not
> just the last one?
> 
> Thank you,
> b.
> 
> root <- function(var)
> {
> #---Phillips-Perron
> PP.test(var, lshort = TRUE) 
> PP.test(var, lshort = FALSE) 
> 
> #---Augmented Dickey-Fuller 
> adf.test(var, alternative = "stationary", k =
> trunc((length(var)-1)^(1/3)))
> 
> #---KPSS
> kpss.test(var, null = "Level", lshort = TRUE)
> kpss.test(var, null = "Trend", lshort = FALSE)
> }
> 


You should store all your results in a list and return the list:

root <- function(var) {
   # create empty list
   ret <- list()

   #---Phillips-Perron
   ret[[1]] <- PP.test(var, lshort = TRUE)
   ret[[2]] <- PP.test(var, lshort = FALSE)

   #---Augmented Dickey-Fuller
   ret[[3]] <- adf.test(var, alternative = "stationary",
                        k = trunc((length(var)-1)^(1/3)))

   #---KPSS
   ret[[4]] <- kpss.test(var, null = "Level", lshort = TRUE)
   ret[[5]] <- kpss.test(var, null = "Trend", lshort = FALSE)

   # give `ret' some meaningful names
   names(ret) <- c("PP1", "PP2", "ADF", "KPSS1", "KPSS2")

   # return list
   ret
}

results <- root(somevar)

HTH,

--sundar

P.S. Also note my indenting which makes code more readable, especially 
if you expect other to try to read it.




More information about the R-help mailing list