[R] evaluating expressions as R console

Adrian Dușa dusa.adrian at unibuc.ro
Mon Sep 5 01:47:36 CEST 2016


Dear R users,

I am trying to simulate a pseudo R console, evaluating commands. This is a
simple example of a series of command lines which get evaluated:

foo <- function(x) {
    print(x)
}
print)foo)
foo(2)


If I copied and pasted this example in an R console, this is the result to
replicate (and the benchmark to compare everything else):

> foo <- function(x) {
+     print(x)
+ }
> print)foo)
Error: unexpected ')' in "print)"
> foo(2)
[1] 2


The trouble I'm having is to reproduce this exact output, by evaluating the
chunk of code. I tried both Rscript and littler, but I am unable to
reproduce this.

I had some success via:

R CMD BATCH -q foo.R

(saving the chunk to a file called foo.R), which only works until the first
error appears. I can run it again on the subsequent command(s) after the
error, but the function foo(), which in a normal R console gets created
without any error, doesn't get preserved on the next run.

I also had some limited success with:

source("foo.R", echo = TRUE, keep.source = TRUE)

But the error message is different, and the first 4 lines are not echo-ed.

source() works pretty well if there are no errors, but otherwise I get the
same result as R CMD BATCH, namely only the error is displayed and the
function foo() doesn't get created in the current environment.

I would rather use source() than R CMD BATCH, due to specific environments
where the chunk should be evaluated in (not impossible, but inconvenient to
save environments and load them back in the R CMD BATCH).

Was also curious about knitr and pander, but again unable to replicate the
results in the real R console.

After many hours of searching, reading and testing, I would be grateful for
any hint.

Thank you in advance,
Adrian

-- 
Adrian Dusa
University of Bucharest
Romanian Social Data Archive
Soseaua Panduri nr.90
050663 Bucharest sector 5
Romania

	[[alternative HTML version deleted]]



More information about the R-help mailing list