On 10/3/2006 10:46 AM, Lorenzo Isella wrote: > Dear All, > I am trying to use the do.call command to avoid tedious loops in R > when I need to call repetitively a function.
That's probably not the best choice. You might want to think about writing a wrapper for the function instead; you'll end up with easier code to read and debug. > I am experiencing a problem when the arguments of a function are given > with a vector (I need to express then this way to be able later on to > integrate them numerically with the adapt package). > Consider the small script: > > remove(list=ls()) > #library(adapt) > > # first a list of the parameters > > tau<-0.1 > beta<-1/tau > St<-tau > D=2e-2 > q<-2*beta^2*D > lam1<- -beta/2*(1+sqrt(1-4*St)) > lam2<- -beta/2*(1-sqrt(1-4*St)) > x0<- 0 > vx0<- 1 > > # fist a function with scalar parameters > > sigma_pos_old<-function(t,q,lam1,lam2) > { > q/(lam1-lam2)^2*( > (exp(2*lam1*t)-1)/(2*lam1)-2/(lam1+lam2)*(exp(lam1*t+lam2*t)-1) + > (exp(2*lam2*t)-1)/(2*lam2) ) > } > > # now the same function where the only argument t is given as a 1x1 vector > > sigma_pos<-function(myargs) > { > q/(lam1-lam2)^2*( > (exp(2*lam1*myargs[1])-1)/(2*lam1)-2/(lam1+lam2)*(exp(lam1*myargs[1]+lam2*myargs[1])-1) > + (exp(2*lam2*myargs[1])-1)/(2*lam2) ) > } > > # Now I use do.call > > > newtime<-seq(1,5,len=1001) > > mypar<-c(q,lam1,lam2) > sig_xx<-do.call("sigma_pos_old",c(list(t=newtime),mypar)) > > # Now this line does not work; sig_xx2 is not a vector equal to sig_xx > > sig_xx2<-do.call("sigma_pos",c(list(myargs =newtime))) Take a look at what c(list(t=newtime),mypar) gives you: it's a list of length 2. You want a list of length 4. To get that, just use mypar <- list(q, lam1, lam2). Or better still, write a wrapper function, e.g. better_sigma <- function() { sigma_pos_old(t, q, lam1, lam2) } Remember that better_sigma will look up the variables t, q, lam1, and lam2 in whatever environment it was defined in, so if you have a function that modifies local copies of those variables and then calls better_sigma, you should define better_sigma within that function. Duncan Murdoch > > > > > So I am making some mistake with the do.call command, since I get a > single value rather than a vector. > Can anyone tell me what I am doing wrong? I tried several variations > of the syntax, but none works the way I want. > Kind Regards > > Lorenzo > > ______________________________________________ > R-help@stat.math.ethz.ch 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. ______________________________________________ R-help@stat.math.ethz.ch 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.