[R] Splitting a string expression into components

William Dunlap wdunlap at tibco.com
Wed Jul 3 19:55:01 CEST 2013


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.



More information about the R-help mailing list