[R] separate commands by semicolon

David Winsemius dwinsemius at comcast.net
Sat Sep 17 23:12:44 CEST 2016


> On Sep 17, 2016, at 8:28 AM, Adrian Dușa <dusa.adrian at unibuc.ro> wrote:
> 
> There is one minor problem with parse(): if any of the individual commands
> has an error, the entire text will be parsed in a single error.
> 
> For example, in a normal R console:
> 
>> print(2); ls(
> [1] 2
> +
> 
> So first print(2) is executed, and only after the console expects the user
> to continue the command from ls(
> Parsing the same text:
> 
>> parse(text = "print(2); ls(")
> Error in parse(text = "print(2); ls(") :
>  <text>:2:0: unexpected end of input
> 1: print(2); ls(
>   ^
> 
> What I would need is something to separate the two commands, irrespective
> of their syntactical correctness:
> 
> [1] "print(2)" "ls("
> 
> I hope this explains the situation,

Not entirely clear. If you were intending to just get character output then you could just use:

strsplit(txt, ";")

If you wanted parsing to an R expression to occur you could pass through sapply and get a full accounting of the syntactic deficit using `try`:

sapply(strsplit( "print(2); ls(" , ";")[[1]] , function(t) {try(parse(text=t))})
Error in parse(text = t) : <text>:2:0: unexpected end of input
1:  ls(
   ^
expression(`print(2)` = print(2), ` ls(` = "Error in parse(text = t) : <text>:2:0: unexpected end of input\n1:  ls(\n   ^\n")


> Adrian
> 
> On Thu, Sep 15, 2016 at 11:02 PM, Adrian Dușa <dusa.adrian at unibuc.ro> wrote:
> 
>> On Thu, Sep 15, 2016 at 10:28 PM, William Dunlap <wdunlap at tibco.com>
>> wrote:
>> 
>>> The most reliable way to split such lines is with parse(text=x).
>>> Regular expressions don't do well with context-free grammars.
>>> 
>> 
>> Oh, that's right of course.
>>> as.character(parse(text = x))
>> [1] "foo <- \"3;4\""                    "bar <- \"don't ; use semicolons\""
>> 
>> That was simple enough, thanks very much,
>> Adrian
>> 
>> --
>> Adrian Dusa
>> University of Bucharest
>> Romanian Social Data Archive
>> Soseaua Panduri nr.90
>> 050663 Bucharest sector 5
>> Romania
>> 
> 
> 
> 
> -- 
> Adrian Dusa
> University of Bucharest
> Romanian Social Data Archive
> Soseaua Panduri nr.90
> 050663 Bucharest sector 5
> Romania
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list