[R] Splitting a string expression into components

Bert Gunter gunter.berton at gene.com
Wed Jul 3 20:13:15 CEST 2013


Alternatively, perhaps strsplit() with an appropriate regex argument.

See ?strsplit ?regexp

e.g.

strsplit ("z<=5",split = "[<>=]+")
[[1]]
[1] "z" "5"

This of course will only work if you know what the characters are that
define "left" and "right", how complex the expressions might be, etc.
-- i.e. the simple case.

-- Bert

On Wed, Jul 3, 2013 at 10:55 AM, William Dunlap <wdunlap at tibco.com> wrote:
> If your syntax is like R's syntax then parse() can help.
>   R> p <- parse(text="z = 1 + 2")
>   R> p[[1]] # the first (& only) expression in "z = 1 + 2"
>   z = 1 + 2
>   R> as.list(p[[1]]) # the 'function' called (`=`) and its 'arguments'
>   [[1]]
>   `=`
>
>   [[2]]
>   z
>
>   [[3]]
>   1 + 2
>
>   R> as.list(p[[1]][[3]]) # ditto for the 2nd argument above
>   [[1]]
>   `+`
>
>   [[2]]
>   [1] 1
>
>   [[3]]
>   [1] 2
>
> Bill Dunlap
> Spotfire, TIBCO Software
> wdunlap tibco.com
>
>
>> -----Original Message-----
>> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
>> Of Dan Murphy
>> Sent: Wednesday, July 03, 2013 10:38 AM
>> To: R-help at r-project.org
>> Subject: [R] Splitting a string expression into components
>>
>> I have a vector of strings that contain mathematical expressions. E.g.,
>> x <- c("5 <= 7", "z = 1+2")
>> and I would like to decompose each expression into its left- and
>> right-hand-side components etc., output something like
>>
>> "5" "<=" "7"
>> "z" "=" "1" "+" "2"
>>
>> Is there something built into the R language to accomplish this?
>> Thanks for advance.
>> Dan
>>
>>       [[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.
>
> ______________________________________________
> 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.



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm



More information about the R-help mailing list