title: How to convert factors in a data frame to prespecified colour names in R?
body: <p>I'm trying to generate heatmaps for gene expression data which also have columns representing clinical data as can be seen here: <a href="https://www.biostars.org/p/18211/" rel="nofollow">https://www.biostars.org/p/18211/</a></p>
  
  <p>My problem is, both heatmap.plus and heatmap.3 require that the matrix specifying the colours in the heatmap actually be written as colour names. They won't take normal factors in a column and convert them to colours.</p>
  
  <p>This is what my data frame "df" looks like:</p>
  
  <pre><code>sample_name     gender     chemotherapy     clinical_subtype
  sample_01       M          alk              1
  sample_02       F          tmz              2
  sample_03       M          rad              2
  sample_04       M          rad.tmz          4
  sample_05       F          tmz              3
  </code></pre>
  
  <p>I can generate a data frame of the levels of each factor matched to a specific colour using the following code:</p>
  
  <pre><code>gender_colors &lt;- with(df, data.frame(row.names = levels(gender), color = brewer.pal(nlevels(gender), name = 'Set1')))
  </code></pre>
  
  <p>Which looks like the following (with 3 colours because of missing samples):</p>
  
  <pre><code>  color
    #66C2A5
  F #FC8D62
  M #8DA0CB
  </code></pre>
  
  <p>Is there any way to use this data frame to index the original factors, replacing them with their corresponding colour so that my original frame would look something like the following?</p>
  
  <pre><code>sample_name     gender     chemotherapy     clinical_subtype
  sample_01       #8DA0CB    #FC8D62          #FDAE61
  sample_02       #FC8D62    #66C2A5          #FFFFBF
  sample_03       #8DA0CB    #C2294A          #FFFFBF
  sample_04       #8DA0CB    #FA9856          #A6D96A
  sample_05       #FC8D62    #66C2A5          #1A9641
  </code></pre>
  
  <p>If there is an easier way to do this that doesn't require me to generate the intermediate factor level matched data frame to specific colours that would probably be a lot easier, but any help with this issue would be greatly appreciated!</p>
  
  <pre><code>      color
  1     #D7191C
  2     #FDAE61
  3     #FFFFBF
  4     #A6D96A
  5     #1A9641
  </code></pre>