0

I am trying to return a zoo object from a function in R. If I return the zoo object using return from function f e.g. return(zsum), and feed into a variable

   Ret <- lapply(df, f) #, Ret contains a list, not a zoo object.

What I would like to do is run function f repeatedly, and process (plot/save to file/aggregate) the zoo and other objects created by each function call outside the function.

Example:
zoo object within the loop:

 2014-05-30 2014-06-09 2014-06-11 2014-07-17 2014-07-18 2014-07-21 2014-07-24 
      0.61       0.53       0.00       0.57       0.65       0.70       0.92 
2014-07-28 2014-07-31 2014-08-07 2014-08-08 2014-08-11 2014-08-13 2014-08-18 
     1.93       2.11       2.68       2.77       2.90       3.04       4.34 
2014-08-21 2014-08-22 2014-08-25 2014-08-26 2014-08-27 2014-08-28 2014-08-29 
    4.55       4.88       5.26       5.38       5.49       5.58       5.66 
2014-09-02 2014-09-04 
     5.77       5.83      
  [1] "zoo"    

List returned from function:

Ret
$`Medivir AB`
2014-05-30 2014-06-09 2014-06-11 2014-07-17 2014-07-18 2014-07-21 2014-07-24 
  0.61       0.53       0.00       0.57       0.65       0.70       0.92 
 2014-07-28 2014-07-31 2014-08-07 2014-08-08 2014-08-11 2014-08-13 2014-08-18 
   1.93       2.11       2.68       2.77       2.90       3.04       4.34 
 2014-08-21 2014-08-22 2014-08-25 2014-08-26 2014-08-27 2014-08-28 2014-08-29 
   4.55       4.88       5.26       5.38       5.49       5.58       5.66 
2014-09-02 2014-09-04 
   5.77       5.83   
 class(Ret)
[1] "list"

I have tried to create a list containing a zoo object (presumably analogous to passing a reference) as discussed here: Returning multiple objects in an R function

However, attempting this:

 newlist <- list("zsum" = zsum);  
 return(newlist);

produced the following:

 newlist <- list(“"  
 print(newlist);  
 #Error in print(newlist) : object 'newlist' not found  

 return(newlist);  
 #Error: object 'newlist' not found  
 }  
Error: unexpected '}' in "}"    

The function and calls that I am using are:

 f <- function (z) {
 zz <- read.zoo(z, header = TRUE, split = 2, format = "%d/%m/%Y", aggregate = mean);
 z.fill <- na.locf(zz);
 z.fill <- (z.fill >= 0.5) * z.fill;
 z.fill <- na.fill(z.fill,0);
 zfill.mat = matrix(z.fill, NROW(z.fill));
 z.sum <- rowSums(zfill.mat); 
 zsum <- zoo(z.sum,time(z.fill)); 

 newlist <- list("zsum" = zsum);  
 return(newlist);
 } 

 DF <- read.csv(file.choose(), header = TRUE, as.is = TRUE);
 DF.S <- split(DF[-2], DF[[2]]);
 Ret <- lapply(DF.S, f); 

If, instead, I replace newlist <- and return(newlist) simply with return(zsum), it returns a list, not a zoo object, which I cannot plot as it contains a header corresponding to the 'split' element from DF.S <- split(DF[-2], DF[[2]]);

Any help would be much appreciated!

Community
  • 1
  • 1
Carl
  • 598
  • 2
  • 11
  • 25

0 Answers0