title: R wrap function call into another call without using string manipulation
body: <p>I'm looking for a nice way to wrap a function call into another function call. Wrapping a function before it is being called into other functions is easy, but modifying an existing call seems not so straight forward to me.</p>
  
  <p>I found a way which I explain using the example below, but it is basically relying on converting the call into a list into a string, then adding the new call as string and convert everything back to language using <code>str2lang</code>. </p>
  
  <p>Is there a cleaner way to do this?</p>
  
  <p>Lets assume I'm building a custom <code>summarise</code> function for <code>dplyr</code> which will check, whether the output is a vector and in that case create a <code>df-col</code> by using <code>pivot_wider(enframe(...))</code> on the existing call.</p>
  
  <p>Here is the reprex.</p>
  
  
  
  <pre class="lang-r prettyprint-override"><code>library(tidyverse)
  
  short_sum &lt;- function(data, ...) {
  
    fns &lt;- rlang::enquos(...)
  
    fns &lt;- purrr::map(fns, function(x) {
  
      res &lt;- rlang::eval_tidy(x, data = data)
  
      if ((is.vector(res)  || is.factor(res)) &amp;&amp; length(res) &gt; 1) {
  
        # is there a better way to do this (start) ---
        # get expression of call and turn it into a string
        x_expr &lt;- as.character(list(rlang::quo_get_expr(x)))
  
        # construct a string with expression above wrapped in another call
        x_expr &lt;- paste0(
          "pivot_wider(enframe(",
          x_expr,
          "), names_from = name, values_from = value)"
        )
  
        # turn string into language and replace expression in x
        x &lt;- rlang::quo_set_expr(x, str2lang(x_expr))
        # is there a better way to do this (end) ---
  
        x
      } else {
        x
      }
    })
  
      dplyr::summarise(data, !!! fns, .groups="drop")
  }
  
  
  mtcars %&gt;% 
    as_tibble %&gt;% 
    short_sum(quant = quantile(mpg),
              range = range(wt))
  
  #&gt; # A tibble: 1 x 2
  #&gt;   quant$`0%` $`25%` $`50%` $`75%` $`100%` range$`1`  $`2`
  #&gt;        &lt;dbl&gt;  &lt;dbl&gt;  &lt;dbl&gt;  &lt;dbl&gt;   &lt;dbl&gt;     &lt;dbl&gt; &lt;dbl&gt;
  #&gt; 1       10.4   15.4   19.2   22.8    33.9      1.51  5.42
  </code></pre>
  
  <p><sup>Created on 2020-06-14 by the <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex package</a> (v0.3.0)</sup></p>
  
  <p>This question is based on my answer <a href="https://stackoverflow.com/a/62353857/9349302">here</a> where I use the approach above.</p>