[R] How to capture console output in a numeric format

Greg Snow Greg.Snow at imail.org
Fri Jun 24 17:20:55 CEST 2011


Here is one approach (different from capture.output) that I believe accomplishes what you are trying to do:

frtop <- function(){

	out <- numeric(0)
	topenv <- environment()

	fr <- function(x) {   ## Rosenbrock Banana function
    		x1 <- x[1]
    		x2 <- x[2]
    		f <- 100 * (x2 - x1 * x1)^2 + (1 - x1)^2
		topenv$out <- c(topenv$out, f)
    		f
	}

	ans <- optim(c(-1.2,1), fr)

	list(ans=ans, out=out)
}

out <- frtop()

Now out is a list with 2 components, the first is the return value from optim, the second is a vector with all the f values from the evaluation of the fr function.

The basic idea is to wrap everything in a toplevel function, so that it has its own local environment, then define the out vector in the toplevel environment.  We also have a link to that environment through the topenv variable.  Now fr is defined inside of frtop so it can access that environment (lexical scoping) and so when we assign to topenv$out it is doing the assignment in the environment of frtop.  Then we just run optim which calls fr a bunch of times, then output a list with the output and the values at each call.

Hope this helps,


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Ravi Varadhan
Sent: Friday, June 24, 2011 8:40 AM
To: r-help at r-project.org
Subject: [R] How to capture console output in a numeric format

Hi,

I would like to know how to capture the console output from running an algorithm for further analysis.  I can capture this using capture.output() but that yields a character vector.  I would like to extract the actual numeric values.  Here is an example of what I am trying to do.

fr <- function(x) {   ## Rosenbrock Banana function
    on.exit(print(f))
    x1 <- x[1]
    x2 <- x[2]
    f <- 100 * (x2 - x1 * x1)^2 + (1 - x1)^2
    f
}

fvals <- capture.output(ans <- optim(c(-1.2,1), fr))

Now, `fvals' contains character elements, but I would like to obtain the actual numerical values.  How can I do this?

Thanks very much for any suggestions.

Best,
Ravi.

-------------------------------------------------------
Ravi Varadhan, Ph.D.
Assistant Professor,
Division of Geriatric Medicine and Gerontology School of Medicine Johns Hopkins University

Ph. (410) 502-2619
email: rvaradhan at jhmi.edu<mailto:rvaradhan at jhmi.edu>


	[[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