Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy this behavior when coercing a list to character via as.character()?
    text
    copied!<p>In the process of (mostly) answering <a href="https://stackoverflow.com/q/7591295/324364">this</a> question, I stumbled across something that I feel like I really should already have seen before. Let's say you've got a list:</p> <pre><code>l &lt;- list(a = 1:3, b = letters[1:3], c = runif(3)) </code></pre> <p>Attempting to coerce <code>l</code> to various types returns an error:</p> <pre><code>&gt; as.numeric(l) Error: (list) object cannot be coerced to type 'double' &gt; as.logical(l) Error: (list) object cannot be coerced to type 'logical' </code></pre> <p>However, I'm apparently allowed to coerce a list to character, I just wasn't expecting this result:</p> <pre><code>&gt; as.character(l) [1] "1:3" [2] "c(\"a\", \"b\", \"c\")" [3] "c(0.874045701464638, 0.0843329173512757, 0.809434881201014)" </code></pre> <p>Rather, if I'm allowed to coerce lists to character, I would have thought I'd see behavior more like this:</p> <pre><code>&gt; as.character(unlist(l)) [1] "1" "2" "3" "a" "b" [6] "c" "0.874045701464638" "0.0843329173512757" "0.809434881201014" </code></pre> <p>Note that <em>how I specify the list elements originally</em> affects the output of <code>as.character</code>:</p> <pre><code>l &lt;- list(a = c(1,2,3), b = letters[1:3], c = runif(3)) &gt; as.character(l) [1] "c(1, 2, 3)" [2] "c(\"a\", \"b\", \"c\")" [3] "c(0.344991483259946, 0.0492411875165999, 0.625746068544686)" </code></pre> <p>I have two questions:</p> <ol> <li>How is <code>as.character</code> dredging up the information from my original creation of the list <code>l</code> in order to spit out <code>1:3</code> versus <code>c(1,2,3)</code>.</li> <li>In what circumstances would I want to do this, exactly? When would I want to call <code>as.character()</code> on a list and get output of this form?</li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload