Skip to content
Prev 381530 / 398502 Next

decomposing a string representing a valid mathematical expression?

On Tue, 29 Oct 2019 13:55:27 +0100
Witold E Wolski <wewolski at gmail.com> wrote:

            
You might be interested in the `parse` function:

x <- "(a+b) * c/(d * (e - f))"
str(parse(text = x))
# length 1 expression((a + b) * c/(d * (e - f)))
#  - attr(*, "srcref")=List of 1
#   ..$ : 'srcref' int [1:8] 1 1 1 23 1 23 1 1
#   .. ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment: 0x55ebecdac210>
#  - attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile' <environment:0x55ebecdac210>
#  - attr(*, "wholeSrcref")= 'srcref' int [1:8] 1 0 2 0 0 0 1 2
#   ..- attr(*, "srcfile")=Classes 'srcfilecopy', 'srcfile'<environment:0x55ebecdac210>
parse(text = x)[[1]]
# (a + b) * c/(d * (e - f))
parse(text = x)[[1]][1]
# `/`()
parse(text = x)[[1]][2]
# ((a + b) * c)()
parse(text = x)[[1]][3]
# (d * (e - f))()

Quoting ?expression,