Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I think the way to think about the difference between <code>labels</code> and <code>levels</code> (ignoring the <code>labels()</code> function that Tommy describes in his answer) is that <code>levels</code> is intended to tell R which values to look for in the input (<code>x</code>) and what order to use in the levels of the resulting <code>factor</code> object, and <code>labels</code> is to change the <em>values</em> of the levels after the input has been coded as a factor ... as suggested by Tommy's answer, there is no part of the <code>factor</code> object returned by <code>factor()</code> that is called <code>labels</code> ... just the levels, which have been adjusted by the <code>labels</code> argument ... (clear as mud).</p> <p>For example:</p> <pre><code>&gt; f &lt;- factor(x=c("a","b","c"),levels=c("c","d","e")) &gt; f [1] &lt;NA&gt; &lt;NA&gt; c Levels: c d e &gt; str(f) Factor w/ 3 levels "c","d","e": NA NA 1 </code></pre> <p>Because the first two elements of <code>x</code> were not found in <code>levels</code>, the first two elements of <code>f</code> are <code>NA</code>. Because <code>"d"</code> and <code>"e"</code> were included in <code>levels</code>, they show up in the levels of <code>f</code> even though they did not occur in <code>x</code>.</p> <p>Now with <code>labels</code>:</p> <pre><code>&gt; f &lt;- factor(c("a","b","c"),levels=c("c","d","e"),labels=c("C","D","E")) &gt; f [1] &lt;NA&gt; &lt;NA&gt; C Levels: C D E </code></pre> <p>After R figures out what should be in the factor, it re-codes the levels. One can of course use this to do brain-frying things such as:</p> <pre><code>&gt; f &lt;- factor(c("a","b","c"),levels=c("c","d","e"),labels=c("a","b","c")) &gt; f [1] &lt;NA&gt; &lt;NA&gt; a Levels: a b c </code></pre> <p>Another way to think about <code>levels</code> is that <code>factor(x,levels=L1,labels=L2)</code> is equivalent to</p> <pre><code>f &lt;- factor(x,levels=L1) levels(f) &lt;- L2 </code></pre> <p>I think an appropriately phrased version of this example might be nice for Pat Burns's <a href="http://www.burns-stat.com/pages/Tutor/R_inferno.pdf" rel="noreferrer">R inferno</a> -- there are plenty of factor puzzles in section 8.2, but not this particular one ...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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