title: Custom function to manipulate list not working in mutate when it does work in isolation
body: <p>I have a data frame where one column is a list of keystrokes. I have then created a custom function to convert the list of keystrokes into the final word. As a concrete example, I start with this data:</p>
  <pre><code>dat &lt;- data.frame(word=c(1,1,2,2,2,2),
                    key=c(&quot;a&quot;,&quot;b&quot;,&quot;a&quot;,&quot;b&quot;,&quot;Backspace&quot;,&quot;c&quot;))
  </code></pre>
  <p>I then call the below to create a column with lists of keystrokes (the repeats are intentional, as I need to preserve every individual keystroke):</p>
  <pre><code>dat &lt;- dat %&gt;% 
    group_by(word) %&gt;% 
    mutate(key_list = I(list(key))) %&gt;% 
    ungroup()
  </code></pre>
  <p>This creates a data frame where the first 2 rows have key_list = <code>a,b</code> and the last 4 rows are <code>a,b,Backspace,c</code>. This is to be expected.</p>
  <p>I then want to concatenate the key_list into a single string. However, I've created the custom function below because when iterating through the list, if I encounter &quot;Backspace&quot;, I need to delete the last keystroke. Therefore, the function looks like:</p>
  <pre><code>library(tidyverse)
  
  word_list_to_final_str &lt;- function(word_list) {
    final_list = c()
    for (i in word_list) {
      if (tolower(i) %in% c(letters)) {
        final_list &lt;- c(final_list, tolower(i))
      }
      else if (i == 'Backspace') {
        final_list &lt;- head(final_list, -1)
      }
    }
    final_str &lt;- str_c(final_list,collapse=&quot;&quot;)
    return(final_str)
  }
  </code></pre>
  <p>When I run this function in isolation, it returns the correct result:</p>
  <pre><code>19:13:11&gt; word_list_to_final_str(c(&quot;a&quot;,&quot;b&quot;,&quot;Backspace&quot;,&quot;c&quot;))
  [1] &quot;ac&quot;
  </code></pre>
  <p>However, when I run the function within <code>mutate()</code>, I get an additional column with all &quot;abababbackspacecabbackspacecabbackspacecabbackspacec&quot;.</p>
  <pre><code>dat &lt;- dat %&gt;% 
    mutate(final_word = word_list_to_final_str(key_list))
  </code></pre>
  <p>Clearly somewhere the function is not clearing the list, but I cannot understand where. How can I change the function?</p>