title: Creating an object from a chunk of R code without converting to a string
body: <p>I am trying to turn an arbitrary chunk (not in the <code>Rmarkdown</code>sense) of code into an object that I can call to return either (1) the code's output or (2) the code and its output.</p>
  <p>I can produce output (1) by converting the code to a string and then use <code>eval(parse())</code>. However, the issue with this approach is that turning the code into a string means syntax highlighters and linters do not look at the contents of the string and this makes it more difficult to debug. I am therefore looking for alternative approaches. Below I demonstrate what I'm looking for.</p>
  <h2>Start with a chunk of arbitrary code</h2>
  <pre><code>df &lt;- data.frame(x = 1:10)
  print(5)
  #&gt; [1] 5
  df$x + 1
  #&gt;  [1]  2  3  4  5  6  7  8  9 10 11
  </code></pre>
  <h2>Current Approach: convert chunk to string</h2>
  <pre class="lang-r prettyprint-override"><code>my_code &lt;- &quot;
  df &lt;- data.frame(x = 1:10)
  print(5)
  df$x + 1
  &quot;
  eval(parse(text = my_code))
  #&gt; [1] 5
  #&gt;  [1]  2  3  4  5  6  7  8  9 10 11
  </code></pre>
  <h2>Desired Approach (psuedo-code): wrap chunk in <code>foo{}</code>, call object</h2>
  <pre class="lang-r prettyprint-override"><code># Wrap in some function
  my_code &lt;- foo{
  df &lt;- data.frame(x = 1:10)
  print(5)
  df$x + 1
  }
  </code></pre>
  <h2>Two possible types of outputs expected</h2>
  <h4>Output option #1: shows code, shows output</h4>
  <pre class="lang-r prettyprint-override"><code># Call object
  my_code
  
  df &lt;- data.frame(x = 1:10)
  print(5)
  #&gt; [1] 5
  df$x + 1
  #&gt;  [1]  2  3  4  5  6  7  8  9 10 11
  </code></pre>
  <h4>Output #2: doesn't show code, shows output</h4>
  <pre class="lang-r prettyprint-override"><code># Call object
  my_code
  #&gt; [1] 5
  #&gt;  [1]  2  3  4  5  6  7  8  9 10 11
  </code></pre>