title: Assign values to a variable, conditional on a factor variable
body: <p>I want to create a variable that takes values from a numeric vector, conditional on a factor variable.</p>
  
  <p>I have a numeric vector </p>
  
  <pre><code>x &lt;- c(0, 1000, 50000)
  </code></pre>
  
  <p>And a data frame:</p>
  
  <pre><code>df &lt;- data.frame(ID = seq(1:8), z = c("A", "A", "C", NA, "B", "A", NA, NA)) 
  </code></pre>
  
  <blockquote>
  <pre><code>   ID    z
   1  1    A
   2  2    A
   3  3    C
   4  4 &lt;NA&gt;
   5  5    B
   6  6    A
   7  7 &lt;NA&gt;
   8  8 &lt;NA&gt; 
  </code></pre>
  </blockquote>
  
  <p>I want to create a variable <code>y</code> taking the value <code>x[1]</code> if <code>z=="A"</code>, <code>x[2]</code> if <code>z=="B"</code>, and <code>x[3]</code> if <code>z=="C"</code>.</p>
  
  <p>My desired output</p>
  
  <blockquote>
  <pre><code>   ID    z   y
  1   1    A   0
  2   2    A   0
  3   3    C   50000
  4   4    NA  NA
  5   5    B   1000
  6   6    A   0
  7   7    NA  NA
  8   8    NA  NA
  </code></pre>
  </blockquote>
  
  <p>I tried with</p>
  
  <pre><code>df$y[which(df$z == "A")] &lt;- x[1]
  df$y[which(df$z == "B")] &lt;- x[2]
  df$y[which(df$z == "C")] &lt;- x[3]
  </code></pre>