Skip to content
Prev 263639 / 398502 Next

How to capture console output in a numeric format

Thank you very much, Jim.  That works!  

I did know that I could process the character strings using regex, but was also wondering if there was a direct way to get this.  

Suppose, in the current example I would like to obtain a 3-column matrix that contains the parameters and the function value:

fr <- function(x) {   ## Rosenbrock Banana function
    on.exit(print(cbind(x1, x2, 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, I need to tweak your solution to get the 3-column matrix.  It would be nice, if there was a more direct way to get the numerical output, perhaps a numeric option in capture.output().

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

-----Original Message-----
From: jim holtman [mailto:jholtman at gmail.com] 
Sent: Friday, June 24, 2011 10:48 AM
To: Ravi Varadhan
Cc: r-help at r-project.org
Subject: Re: [R] How to capture console output in a numeric format

try this:
+    on.exit(print(f))
+    x1 <- x[1]
+    x2 <- x[2]
+    f <- 100 * (x2 - x1 * x1)^2 + (1 - x1)^2
+    f
+ }
[1] 24.20000000000000  7.09529600000000 15.08000000000000  4.54169600000000
  [5]  6.02921600000000  4.45625600000000  8.87993600000000  7.77785600000000
  [9]  4.72812500000000  5.16790100000000  4.21000000000000  4.43767000000000
 [13]  4.17898900000000  4.32602300000000  4.07081300000000  4.22148900000000
 [17]  4.03981000000000  4.89635900000000  4.00937900000000  4.07713000000000
 [21]  4.02079800000000  3.99360000000000  4.02458600000000  4.11762500000000
 [25]  3.99311500000000  3.97608100000000  3.97108900000000  4.02390500000000
 [29]  3.98080700000000  3.95257700000000  3.93217900000000  3.93534500000000
On Fri, Jun 24, 2011 at 10:39 AM, Ravi Varadhan <rvaradhan at jhmi.edu> wrote: