[R] Function try and Results of a program

David Winsemius dwinsemius at comcast.net
Sat Sep 4 19:24:53 CEST 2010


On Sep 4, 2010, at 12:41 PM, Evgenia wrote:

>
> David,
>
> your suggestion about try works  perfect for me.
>
> I still have a problem with sink. Could you explain me better your
> suggestion?
>

When you sink to a file, you will continue sending console output to  
that file until you issue sink(). And every time you do it it creates  
an extra layer of redirection (the help page calls these "diversions")  
that will need to be undone to get back to regular console behavior.

?sink     # yes, one needs to R~all~TM

If you wanted a record of what that function was doing you would need  
to:

a) initialize the file with append=FALSE outside the loop (not sure if  
you need to do that, but it does help to get rid of earlier failed  
efforts as well
b) open the sink file with append=TRUE inside the function
c) cat() the two matrices separately since lists cannot be cat()- 
ted,,, and
d)"unsink" with sink() at the end of the function.


  sink("example.txt", append=FALSE); cat("\n" ); sink() #blank line to  
initialize

  fun<-function(data){ data<-as.matrix(data)
       sink("example.txt", append=TRUE); cat("\nEstimate : ", i, "\n" )
       d<-data%*%t(data); cat("d= \n",d, "\n")
       s<-solve(d);       cat("s= \n",s, "\n")
       out<-list(s=s,d=d);  sink()
       return(out)
      }
>
>
> View this message in context: http://r.789695.n4.nabble.com/Function-try-and-Results-of-a-program-tp2526621p2526822.html
> Sent from the R help mailing list archive at Nabble.com.
-- 

David Winsemius, MD
West Hartford, CT


#------------
An unfortunate effect of Nabble use is that it leads one to believe  
that the entire world sees your earlier postings:
#-------------
f<-function(n,mean1){
a<-matrix(rnorm(n, mean1 , sd = 1),ncol=5)
b<-matrix(runif(n),ncol=5)
data<-rbind(a,b)
out<-data
out}

*********I want to simulate 1000 datasets (here only 5) so I use
S<-list()

for (i in 1:5){
S[[i]]<-f(n=10,mean1=0)}

******I have a very complicated function  for estimation of a model  
which I
want to apply to Each one of the above simulated datasets

fun<-function(data){data<-as.matrix(data)
sink(' Example.txt',append=TRUE)
          cat("\n***********************\nEstimation
\n********************\nDataset Sim : ",
            i )
d<-data%*%t(data)
s<-solve(d)
print(s)
out<-list (s,d)
out
}
results<-list()
for(i in 1:5){
     tmp <- try(fun(data=S[[i]]))
     results[[i]] <- ifelse(is(tmp,"try-error"),NA,tmp)
}

####My problem is that results have only the 1st element of the result  
lists
of fun (i.e. only ####although tmp gives me both s and d.



More information about the R-help mailing list