[R] Function try and Results of a program

David Winsemius dwinsemius at comcast.net
Sat Sep 4 17:35:56 CEST 2010


On Sep 4, 2010, at 6:10 AM, Evgenia wrote:

>
> Hello, users.
>
> Dear users,
>
> *******I have a function f to simulate data from a model (example  
> below used
> only to show my problems)
>
> 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.

Two problems:
One:  is the misguided use of unmatched sink calls resulting in an  
accumulation of diversions of the R output. If your run that at the  
console you need to type sink() five times to get any response back  
from the console.

Two: the misguided use of ifelse when you should be using if () 
{}else{} to test a single condition and execute conditional  
assignment. ifelse if for working with vectors, not with lists.

Suggestions:
use the append = TRUE parameter to sink and unsink at the end of that  
function

I'm not sure about how you are using the test for error but since you  
did not construct any errors I cannot really be too sure. If it is  
"working " for you then use this instead:

if (is(tmp,"try-error") ){results[[i]] <- NA} else{results[[i]] <- tmp}

-- 
David.


>
> Thanks
>
> Evgenia
>
>
> -- 
> View this message in context: http://r.789695.n4.nabble.com/Function-try-and-Results-of-a-program-tp2526621p2526621.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list