[R] evaluating expressions as R console

Bert Gunter bgunter.4567 at gmail.com
Mon Sep 5 16:33:17 CEST 2016


I'm sharing this with r-help, as your detailed response might help
others help you.

-- Bert
Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Sun, Sep 4, 2016 at 11:45 PM, Adrian Dușa <dusa.adrian at unibuc.ro> wrote:
> On Mon, Sep 5, 2016 at 2:52 AM, Bert Gunter <bgunter.4567 at gmail.com> wrote:
>>
>> You might want to look at the "evaluate" package.
>
>
> Of course, forgot to mention. I did try it, but got:
>
>> bar <- readLines("foo.R", warn = FALSE)
>> bar <- paste(bar, collapse = "\n")
>> evaluate::evaluate(input = bar)
> [[1]]
> $src
> [1] "foo <- function(x) {\n    print(x)\n}\nprint)foo)\nfoo(2)"
>
> attr(,"class")
> [1] "source"
>
> [[2]]
> <simpleError: <text>:4:6: unexpected ')'
> 3: }
> 4: print)
>         ^>
>
> I ran into the same problem as source(): it works only if it doesn't have
> any errors. In addition, the error message is also different because it
> evaluates the entire chunk, whereas the R console evaluates one command
> (line) at a time.
>
> Fixing the command:
> bar2 <- "foo <- function(x) {\n    print(x)\n}\nprint(foo)\nfoo(2)"
>
> will fix the workflow in evaluate():
>
> evaluate::evaluate(input = bar2)
>
>
> But it will also fix it with source():
>
>> source("foo2.R", echo = TRUE, keep.source = TRUE)
>
>> foo <- function(x) {
> +     print(x)
> + }
>
>> print(foo)
> function(x) {
>     print(x)
> }
>
>> foo(2)
> [1] 2
>
>
> So evaluate() has more detail than source(), but essentially they do the
> same thing in evaluating the whole chunk. From the help of source():
> "Since the complete file is parsed before any of it is run, syntax errors
> result in none of the code being run."
>
> So far, it seems that only R CMD BATCH is able to run one command at a time:
>
> $ R CMD BATCH -q foo.R
> $ cat foo.Rout
>> foo <- function(x) {
> +     print(x)
> + }
>> print)foo)
> Error: unexpected ')' in "print)"
> Execution halted
>
> This error is exactly the same as in the R console, and the function foo()
> is created before the error occurs. One possible solution is to get the
> workspace saved, and run R CMD BATCH again on the rest of commands after the
> error.
>
> But it still needs additional objects if the chunk is to be evaluated in a
> specific environment. This is the point where I've got, and I don't know if
> this is the best approach.
>
> Thank you,
> Adrian
>
> --
> Adrian Dusa
> University of Bucharest
> Romanian Social Data Archive
> Soseaua Panduri nr.90
> 050663 Bucharest sector 5
> Romania



More information about the R-help mailing list