Search code examples
rstringinfix-notation

Converting language type to string in R using infix notation


Let's say that I have the following expression in R:

someExpr <- substitute(a+2*b)

Now I want to look at a subexpression of this, let's say 2*b and generate the string "2*b". I access the subexpression with:

someExpr[[3]]
2 * b

And the type is language and the class is call

typeof(someExpr[[3]])
[1] "language"

I tried to convert this naively with toString and as.character, but then I always get the prefix order:

toString(someExpr[[3]])
[1] "*, 2, b"
as.character(someExpr[[3]])
[1] "*" "2" "b"

Is it possible to get the string in infix notation?


Solution

  • You can use deparse :

    someExpr <- substitute(a+2*b)
    result<-deparse(someExpr[[3]])
    result
    [1] "2 * b"
    
    str(result)
    chr "2 * b"