rparsingcolon-equals

deparse expressions containing `:=`?


Expressions containing := don't deparse nicely :

call1 <- quote(f(a = b(c = d)))
call2 <- quote(f(a := b(c := d)))

# nice
deparse(call1)
#> [1] "f(a = b(c = d))"

# not nice
deparse(call2)
# [1] "f(`:=`(a, b(`:=`(c, d))))"

I would like to get the following output from call2 : "f(a := b(c := d))".

I'm looking for a general solution that deparses := just like = or <- in all situations.


A workaround

This workaround uses the fact that <<- has similar or same precedence and is not often used. I substitute := by <<- in the original call, then it deparses nicely, and I gsub it back to :=. I would like a clean and general solution though.

gsub("<<-",":=", deparse(do.call(
  substitute, list(call2, list(`:=` = quote(`<<-`))))))
#> [1] "f(a := b(c := d))"

Solution

  • You can achieve your desired result using rlang::expr_deparse() which offers some printing improvements.

    rlang::expr_deparse(call2)
    
    [1] "f(a := b(c := d))"