title: Extracting nth position from space-separated string in dplyr
body: <p>I have a dataframe that looks something like this:</p>
  
  <pre><code>data &lt;- data.frame(label = c('S', 'SH', 'S', 'S', 'SH'),
                 word = c('sip', 'shoe', 'plaster', 'reception', 'reception'),
                 word.segs = c('S IH1 P', 'SH UW1', 'P L AE1 S T AH0', 'R AH0 S EH1 P SH AH0 N', 'R AH0 S EH1 P SH AH0 N'),
                 seg.index = c(1, 1, 4, 3, 6))
  </code></pre>
  
  <p>'word.segs' contains a phonetic transcription of the words in the 'word' column, and the value in 'seg.index' refers to the segment of interest - the nth segment in that transcription. What I want to do is to create two new columns containing the two segments <em>after</em> this, i.e. seg.index+1 and seg.index+2.</p>
  
  <p>I've tried it in the following loop, which works but it takes absolutely ages (and I have 100k rows, so it's important to have an efficient solution here)</p>
  
  <pre><code>for (x in 1:nrow(data)){
    data[x, ]$fol.seg = unlist(data$word.segs[x])[data[x, ]$seg.index+1]
    data[x, ]$fol.seg2 = unlist(data$word.segs[x])[data[x, ]$seg.index+2]
  }
  </code></pre>
  
  <p>(note that I've also tried only unlisting once, saving this to a separate object and then extracting the two values of interest, but this doesn't appear to be significantly faster)</p>
  
  <p>I also tried an alternative in dplyr in the hope that it might be more efficient:</p>
  
  <pre><code>data &lt;- data %&gt;%
    mutate(fol.seg = word.segs %&gt;%
    strsplit(split = " ") %&gt;%
    unlist() %&gt;%
    nth(seg.index+1))
  </code></pre>
  
  <p>But I get the following error message, and I have no idea why it's not working:</p>
  
  <blockquote>
    <p>Error in mutate_impl(.data, dots) : 
      Evaluation error: length(n) == 1 is not TRUE.</p>
  </blockquote>
  
  <p>Any help would be greatly appreciated!</p>