title: R: Add new column to dataframe using function
body: <p>I have a data frame <code>df</code> that has two columns, <strong>term</strong> and <strong>frequency</strong>. I also have a list of terms with given IDs stored in a vector called <code>indices</code>. To illustrate these two info, I have the following:</p>
  
  <pre><code>&gt; head(indices)
     Term
  1    hello
  256  i
  33   the
  </code></pre>
  
  <p>Also, for the data frame.</p>
  
  <pre><code>&gt; head(df)
     Term  Freq
  1  i     24
  2  hello 12
  3  the   28
  </code></pre>
  
  <p>I want to add a column in <code>df</code> called <code>TermID</code> which will just be the index of the term in the vector <code>indices</code>. I have tried using <code>dplyr::mutate</code> but to no avail. Here is my code below</p>
  
  <pre><code>library(dplyr)
  
  whichindex &lt;- function(term){
                ind &lt;- which(indices == as.character(term))
                ind}
  
  mutate(df, TermID = whichindex(Term))
  </code></pre>
  
  <p>What I am getting as output is a <code>df</code> that has a new column called <code>TermID</code>, but all the values for <code>TermID</code> are the same. </p>
  
  <p>Can someone help me figure out what I am doing wrong? It would be nice as well if you can recommend a more efficient algorithm to do this in [R]. I have implemented this in Python and I have not encountered such issues.</p>
  
  <p>Thanks in advance.</p>