[R] Using capture.output within a function
Duncan Murdoch
murdoch.duncan at gmail.com
Fri Sep 2 12:07:35 CEST 2011
On 11-09-02 5:24 AM, Kristian Lind wrote:
> Dear R-users
>
> I'm running a maximum likelihood procedure using the spg package. I'd like
> to save some output produced in each iteration to a file, but if I put the
> capture.output() within the function I get the following message; Error in
> spg(par = startval, fn = loglik, gr = NULL, method = 3, lower = lo, :
> Failure in initial function evaluation!Error in -fn(par, ...) : invalid
> argument to unary operator
It looks as though you put capture.output() last in your function, so
the result of the function is the result of the capture.output call, not
the function value.
Duncan Murdoch
>
> I have considered putting the capture.output() after the function, but there
> are some issues with R stalling on me so I'd like that the output is saved
> for each iteration and not only at completion.
>
> Any suggestions on how to get this done would be much appreciated.
>
> Kristian Lind
>
> *Below an example of what I'm trying to do...*
>
>
> loglik<- function(w){
>
> state<- c( b_1 = 0,
> b_2 = 0,
> a = 0)
> #declaring ODEs
> Kristian<-function(t, state, w){
> with(as.list(c(state, w)),
> {
> db_1 = -((w[1]+w[8])*b_1+(w[2]+w[6]*w[8]
> +w[7]*w[9])*b_2+0.5*(b_1)^2+w[6]*b_1*b_2+0.5*
> ((w[6])^2+(w[7])^2)*(b_2)^2)
> db_2 = -w[3]*b_2+1
> da = w[1]*w[4]*b_1+(w[2]*w[4]+w[3]*w[5])*b_2
> list(c(db_1, db_2, da))
> })
> }
>
> # time making a sequence from t to T evaluated at each delta seq(t, T,
> by = delta)
> times<- seq(0, 10, by = 0.5)
>
> outmat<- ode(y = state, times = times, func = Kristian, parms = w)
> print(w)
> print(outmat)
> .
> .
> .
> f<-rep(NA, 1)
> f[1]<- 1/(T-1)*sum(log(pJ$p)-log(pJ$J))
> f
> capture.output(outmat, file = "spgoutput.txt", append = TRUE)
> }
> fit<- spg(fn =loglik, ...)
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
More information about the R-help
mailing list