5

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))"
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
  • May I ask (out of curiosity) what the application is? – s_baldur May 17 '19 at 14:23
  • 1
    it's to log operations, for debugging or for demos, try this : ```':=' <- `<-`; showcase <- function(x, msg = NULL){if (!is.null(msg)) message(msg); call_chr <- rlang::expr_deparse(substitute(x)); cat("> ", call_chr,"\n"); print(x)}; showcase(cars_head := head(cars,2), "display head of cars")``` – moodymudskipper May 17 '19 at 16:23

1 Answers1

3

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))"
Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
  • This solution serves me well and expr_deparse also shows nicely the question mark operator. However in my benchmark expr_deparse is around 300 times slower than base::deparse, so I'm welcoming any alternative using base R – moodymudskipper Sep 06 '19 at 13:40